<?php 
error_reporting (E_ALL ^ E_NOTICE); if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Author      : Herpan / 31/09/2014 / controller for import price list
Revisi      : Fachri
Revisi      : Dhidhik / 18 Feb 2016 ,controller for importfile
Revisi      : Fachri / 05-2016, Import Inventory, Import Asset
*/

class Import_transaction extends CI_Controller {	
    // inisialisasi manual
    public $menu_id =  109;
    public $menu_model = 'm_import_transaction';
	public $arr_number = array('PI' => array(), 'SI' => array());
	 
    public function __construct() {
        parent::__construct();
		$this->load->model($this->menu_model);
		$this->load->helper('regex');
		$this->load->helper('message');
		$this->load->helper('status');
		$this->load->helper('custom_string');
		$this->load->helper('notices_import_file');                        
	
		$this->load->model('list/m_customer');
		$this->load->model('list/m_items');
		$this->load->model('list/m_vendors');
		$this->load->model('list/m_purchase_requisition');
		$this->load->model('list/m_purchase_order');
		$this->load->model('list/m_sales_quotation');
		$this->load->model('list/m_sales_order');	
		$this->load->model('list/m_account_journal');
		$this->load->model('list/m_fixed_asset_type');
		$this->load->model('list/m_journalvoucher');
		$this->load->model('list/m_inventories');
		$this->load->model('list/m_sales_invoice');	
		$this->load->model('list/m_purchase_invoice');	
		$this->load->model('list/m_receive_item');	
		$this->load->model('m_import_ri');	
		
    }	
	
    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');	
					// set data
					$data['menu_id'] =  $this->menu_id;
					//$data['menu_model'] = $this->menu_model;
			
					// get link from tbl_menu 
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
			
					// get label from tbl_menu 
					$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);	
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);	
					
					$this->load->view('v_header');
					$this->load->view('exim_transaction/v_import_transaction',$data);
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }	
    }
	
	public function edit() {	
        // set data
        $data['menu_id'] =  $this->menu_id;
        //$data['menu_model'] = $this->menu_model;

        // get link from tbl_menu 
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
		$id                     = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
        $data['detail']         = $this->m_import_transaction->get_detail($id);
		
        // get label from tbl_menu 
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);		
        $this->load->view('v_header');
        $this->load->view('exim_transaction/v_edit_import',$data);
        $this->load->view('v_footer');		
    }
	
    //Function Menampilkan Data Pada Data Grid View
    public function ajax(){
        echo $this->m_import_transaction->get_all_history($this->ho);			
    }	

   function detail($id, $trans_type){
	
	    if($trans_type == 'Inventories'){
			echo $this->m_import_transaction->get_detail_history_inventori($id);
		}
		else if($trans_type == 'Asset'){
			echo $this->m_import_transaction->get_detail_history_asset($id);
		}
		else{
			echo $this->m_import_transaction->get_detail_history($id, $trans_type);
		}		
   }	
	
	public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status']   = false;

        if ($modus == 'insert') {
            $result['message']  = 'Import Gagal Data Insert Bernilai Nol, Roll Back';
        }
		else if ($modus == 'journal') {
            $result['message']  = 'Pengaturan Preference Journal Template belum lengkap, silahkan atur ulang';
        }
        
        echo json_encode($result);
        die();
    }
	
	public function insert(){
		$type = $this->input->post('transaction_type');
		
		if($type == 'so'){
		    $this->import_sales_order();
		}
		elseif($type == 'sq'){
		     $this->import_sales_quotation();
		}
		elseif($type == 'do'){
		     $this->import_delivery_order();
		}
		elseif($type == 'si'){
		     $this->import_sales_invoice();
		}
		elseif($type == 'sr'){
		    $this->import_sales_return();
		}
		elseif($type == 'srec'){
		    $this->import_sales_receipt();
		}
		elseif($type == 'preq'){
		    $this->import_purchase_requisition();
		}
		elseif($type == 'po'){
		    $this->import_purchase_order();
		}
		elseif($type == 'ri'){
		    $this->import_receive_item();
		}
		elseif($type == 'pi'){
		    $this->import_purchase_invoice();
		}
		elseif($type == 'pr'){
		    $this->import_purchase_return();
		}
		elseif($type == 'ppay'){
		    $this->import_purchase_payment();
		}
		elseif($type == 'Item_no'){
		    $this->import_item();
		}
		elseif($type == 'Item_inventories'){
		    $this->import_item_inventories();
		}
		elseif($type == 'Item_noninventories'){
		    $this->import_expense();
		}
		elseif($type == 'Fix_asset'){
		    $this->import_asset();
		}
		elseif($type == 'Cust'){
		    $this->import_cust();
		}
		elseif($type == 'Vendor'){
		    $this->import_vendor();
		}
		elseif($type == 'Ar_transaction'){
		    $this->import_ar_transaction();
		}
		elseif($type == 'Ap_transaction'){
		    $this->import_ap_transaction();
		}
		elseif($type == 'ri'){
		    $this->import_receive_item();
		}
		else{
		   echo json_encode(array('status'=>true, 'message'=> 'Transaction Type Is Not Found'));
		}
	}
	
    public function import_receive_item(){
		 try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];

            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
                $objWriter      = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount     = $objPHPExcel->getSheetCount();

                //================ RULE BARU ==============================//
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				
				if(notCaseSensitifNotSpace($sheetData[3]['A'])!=notCaseSensitifNotSpace("Vendor No.")){
					throw new Exception("Maaf transaksi upload gagal Header Vendor No. tidak berada di kolom [A] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['B'])!=notCaseSensitifNotSpace("Vendor Name")){
					throw new Exception("Maaf transaksi upload gagal Header Vendor Name tidak di kolom [B] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['C'])!=notCaseSensitifNotSpace("Ship Date")){
					throw new Exception("Maaf transaksi upload gagal Header Ship Date tidak di kolom [C] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['D'])!=notCaseSensitifNotSpace("Terms Net Days")){
					throw new Exception("Maaf transaksi upload gagal Header Ship Date tidak di kolom [D] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['E'])!=notCaseSensitifNotSpace("Form No.")){
					throw new Exception("Maaf transaksi upload gagal Header Form No. tidak di kolom [E] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['F'])!=notCaseSensitifNotSpace("Receipt No.")){
					throw new Exception("Maaf transaksi upload gagal Header Receipt No. tidak di kolom [F] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['G'])!=notCaseSensitifNotSpace("Receive Date")){
					throw new Exception("Maaf transaksi upload gagal Header Receive Date tidak di kolom [G] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['H'])!=notCaseSensitifNotSpace("Description")){
					throw new Exception("Maaf transaksi upload gagal Header Description tidak di kolom [H] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['I'])!=notCaseSensitifNotSpace("Status")){
					throw new Exception("Maaf transaksi upload gagal Header Status tidak di kolom [I] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['J'])!=notCaseSensitifNotSpace("Item No.")){
					throw new Exception("Maaf transaksi upload gagal Header Item No. tidak di kolom [J] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['K'])!=notCaseSensitifNotSpace("Item Description")){
					throw new Exception("Maaf transaksi upload gagal Header Item Description tidak di kolom [K] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['L'])!=notCaseSensitifNotSpace("Quantity")){
					throw new Exception("Maaf transaksi upload gagal Header Item Quantity tidak di kolom [L] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['M'])!=notCaseSensitifNotSpace("Unit Price")){
					throw new Exception("Maaf transaksi upload gagal Header Unit Price tidak di kolom [M] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['N'])!=notCaseSensitifNotSpace("Rate")){
					throw new Exception("Maaf transaksi upload gagal Header Rate tidak di kolom [N] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['O'])!=notCaseSensitifNotSpace("Amount")){
					throw new Exception("Maaf transaksi upload gagal Header Amount tidak di kolom [O] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['P'])!=notCaseSensitifNotSpace("Tax code")){
					throw new Exception("Maaf transaksi upload gagal Header Tax code tidak di kolom [P] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['Q'])!=notCaseSensitifNotSpace("Item Category")){
					throw new Exception("Maaf transaksi upload gagal Header Item Category tidak di kolom [Q] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['R'])!=notCaseSensitifNotSpace("PO No.")){
					throw new Exception("Maaf transaksi upload gagal Header PO No. tidak di kolom [R] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['S'])!=notCaseSensitifNotSpace("PO Date")){
					throw new Exception("Maaf transaksi upload gagal Header PO Date tidak di kolom [S] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['T'])!=notCaseSensitifNotSpace("Vendor Currency")){
					throw new Exception("Maaf transaksi upload gagal Header Vendor Currency tidak di kolom [T] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[3]['U'])!=notCaseSensitifNotSpace("Branch")){
					throw new Exception("Maaf transaksi upload gagal Header Branch tidak di kolom [U] silahkan periksa kembali");
				}
				
				$this->db->trans_begin();
				$Receipt_no_loop = '';
				$PONumber_loop 	= '';
				$sourceDate     = date('Y-m-d');
				$TransType      = 'RI';
				$DataType       = 'Insert';
				$status         = 1;		
				$num            = $this->m_import_transaction->num_importtrans();
				$number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
				$data_hisimport = array(
					'ImportTransID' => $num,
					'TransType' 	=> $TransType, 
					'DataType'      => $DataType, 
					'ImportStatus' 	=> $status,
					'LastEdited' 	=> date('Y-m-d'),
					'LastUser'      => $this->session->userdata('username')
				);
				$insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
				
				for($i=4; $i<=$lastRow; $i++){
					$VendorNo       = $sheetData[$i]['A'];
					$VendorName     = $sheetData[$i]['B'];
					$Ship        	= $sheetData[$i]['C'];
					$Term        	= $sheetData[$i]['D'];
					$FormNo        	= $sheetData[$i]['E'];
					$ReceiptNo      = $sheetData[$i]['F'];
					$ReceiptDate    = $sheetData[$i]['G'];
					$Desc      		= $sheetData[$i]['H'];
					$Status      	= $sheetData[$i]['I'];
					$ItemNo      	= $sheetData[$i]['J'];
					$ItemDesc      	= $sheetData[$i]['K'];
					$Qty      		= $sheetData[$i]['L'];
					$UnitPrice      = $sheetData[$i]['M'];
					$Rate      		= $sheetData[$i]['N'];
					$Amount      	= $sheetData[$i]['O'];
					$Tax      		= $sheetData[$i]['P'];
					$CategoryName   = $sheetData[$i]['Q'];
					$PONumber   	= $sheetData[$i]['R'];
					$PODate   		= $sheetData[$i]['S'];
					$Currency   	= $sheetData[$i]['T'];
					$Branch   		= $sheetData[$i]['U'];
					
					$usage_date     	= explode(" ",$ReceiptDate);
                    $mont_usage     	= dateMMMtoMM($usage_date[1]);
                    $PODate_Exp    		= $usage_date[2].'-'.$mont_usage.'-'.$usage_date[0];
					
					$po_date     		= explode(" ",$PODate);
                    $montpo_usage     	= dateMMMtoMM($po_date[1]);
                    $ReceiptDate_Exp    = $po_date[2].'-'.$montpo_usage.'-'.$po_date[0];
					
					$prec_no = $this->m_receive_item->create_ri_number(date('Y-m-d'));
					$preq_no = $this->m_purchase_requisition->create_pr_number(date('Y-m-d'));
					$pord_number = $this->m_purchase_order->create_po_number(date('Y-m-d'));
					
					/*
						Get Pajak
					*/
					if($Tax == "T"){
						$get_tax = $this->m_import_transaction->taxes_code('PPN');
						$TotalTax = $Amount * ($get_tax->TaxesRate / 100);
						$ppn_status = $get_tax->TaxesRate;
						$po_tax_status = 1;
					}
					else{
						$TotalTax = 0;
						$ppn_status = 0;
						$po_tax_status = 0;
					}
					
					$get_vendor_code 	= $this->m_import_transaction->get_vendor_code($Branch, $VendorNo);
					
					
					/*
						Get Item Or Jasa
					*/
					if($CategoryName == "Jasa"){
						
						
						
					}
					else{
						$get_item_code = $this->m_import_transaction->get_item_master($ItemDesc);
						
						$ItemType = 0;
						$ItemStatus = 0;
					}
					
					$get_item_code = $this->m_import_transaction->get_item_expense($ItemDesc);
					if($get_item_code != false){
						$ItemType = 1;
						$ItemStatus = 2;
						
						$ItemCode = $get_item_code->ItemCode;
						$ItemDesc = $get_item_code->ItemDesc;
						$ItemUnit = $get_item_code->ItemUnit;
						$ItemCategoryID 	= $get_item_code->ItemCategoryID;
						$ItemCategoryCode 	= $get_item_code->ItemCategoryCode;
					}
					else{
						$get_item_code_master = $this->m_import_transaction->get_item_master($ItemDesc);
						if($get_item_code_master != false){
							$ItemType = 0;
							$ItemStatus = 0;
							
							$ItemCode = $get_item_code_master->ItemCode;
							$ItemDesc = $get_item_code_master->ItemDesc;
							$ItemUnit = $get_item_code_master->ItemUnit;
							$ItemCategoryID 	= $get_item_code_master->ItemCategoryID;
							$ItemCategoryCode 	= $get_item_code_master->ItemCategoryCode;
						}
						else{
							throw new Exception("Maaf Transaksi gagal dibuat Item dengan nama ".$ItemDesc." tidak ada di item master");
						}
					}
					/*==================End=========*/
					if ($get_vendor_code == false) {
                        throw new Exception("Maaf Transaksi gagal dibuat Vendor dengan nama ".$VendorName." tidak ada di vendor master");
                    }
					else{
						if($Receipt_no_loop != $ReceiptNo){
							$data_ri = array(
								'BranchCode' => $Branch,
								'VendorCode' => $get_vendor_code->VendorCode,
								'PRecNumber' => $prec_no,
								'PRecDate' => date('Y-m-d'),
								'POrdDate' => date('Y-m-d'),
								'POrdNumber' => NULL,
								'VendorDONumber' => "",
								'ShipmentDate' => date('Y-m-d'),
								'ShipmentID' => 1,
								'TermsPaymentID' => $get_vendor_code->TermsPaymentID,
								'FOBID' => 1,
								'CurrencyCode' => $Currency,
								'CurrencyRate' => $Rate,
								'OldReceiveNumber' => $ReceiptNo,
								'PRecDesc' => "Import ,PR,PO,Receive Item",
								'PRecSubTotal' => $Amount,
								'PRecPPn10Pcnt' => $ppn_status,
								'PRecPPn10' => $TotalTax,
								'PRecTotalAmount' => ($Amount + $TotalTax),
								'PRecTaxesStatus' => $po_tax_status,
								'PRecInTaxStatus' => 0,
								'TransStatus' => 1,
								'AppLevel1Status' => 1,
								'AppLevel1Code' => $this->session->userdata("username"),
								'AppLevel1Date' => date("Y-m-d", strtotime($txt_date)),
								'CreatedBy' => $this->session->userdata("username"),
								'CreatedAt' => date('Y-m-d'),
								'LastUser' => $this->session->userdata("username")
							);
							$this->m_receive_item->insert($data_ri);
							
							$detail_data = array(
								'PRecNumber' 	=> $prec_no,
								'ItemCode' 		=> $ItemCode,
								'ItemDesc' 		=> $ItemDesc,
								'itemUnit' 		=> $ItemUnit,
								'itemQty' 		=> $Qty,
								'ItemDisc' 		=> 0,
								'ItemPrice' 	=> $UnitPrice,
								'ItemAmount' 	=> $Amount,
								'ItemTaxPPn10' 		=> $TotalTax,
								'ItemTotalAmount' 	=> $Amount + $TotalTax,
								'ItemCategoryID' 	=> $ItemCategoryID,
								'ItemCategoryCode' 	=> $ItemCategoryCode,
								'ItemType'	 		=> $ItemType,
								'ItemStatus' 		=> $ItemStatus,
								'ItemCodeVendor' 	=> " ",
								'LastUser' 			=> $this->session->userdata("username")
							);
							$this->m_receive_item->insert_detail($detail_data);
							
							if($PONumber_loop != $PONumber){
								/*
									Purchase Req
								*/
								$data_preq = array(
									'BranchCode' 		=> $Branch,
									'DepartmentCode' 	=> $this->session->userdata('department'),
									'PReqDate' 			=> date('Y-m-d'),
									'PReqNumber' 		=> $preq_no,
									'AppLevel1Status' 	=> 1,
									'PReqDesc' 			=> "Import ,PR,PO,Receive Item, $Desc, PO Tgl $PODate",
									'AppLevel1Code' 	=> $this->session->userdata("username"),
									'AppLevel1Date' 	=> date("Y-m-d"),
									'TransStatus' 		=> 2,
									'CreatedBy' 		=> $this->session->userdata("username"),
									'CreatedAt' 		=> date('Y-m-d'),
									'OldPReqNumber' 	=> $PONumber,
									'LastUser' 			=> $this->session->userdata("username")
								);
								$this->m_purchase_requisition->insert($data_preq);
								
								$detail_data_preq = array(
									'PReqNumber' => $preq_no,
									'ItemCode' => $ItemCode,
									'ItemDesc' => $ItemDesc,
									'itemUnit' => $ItemUnit,
									'itemQty' => $Qty,
									'ItemQtyPO' => $Qty,
									'ItemQtyRI' => $Qty,
									'ItemQtySpd' => 0,
									'RequiredDate' => date('Y-m-d'),
									'ItemCategoryID' => $ItemCategoryID,
									'ItemCategoryCode' => $ItemCategoryCode,
									'ItemType' => $ItemType,
									'ItemStatus' => $ItemStatus,
									'ItemPPh22Status' => 0,
									'ItemPPh23Status' => 0,
									'ItemAdvNetDueIn' => 0,
									'LastUser' => $this->session->userdata("username")
								);
								$this->m_purchase_requisition->insert_detail($detail_data_preq);
								/*============================End===========================================*/
								
								$data_po = array(
									'BranchCode' => $Branch,
									'VendorCode' => $get_vendor_code->VendorCode,
									'POrdDate' => date('Y-m-d'),
									'POrdNumber' => $pord_number,
									'PReqDate' => date('Y-m-d'),
									'PReqNumber' => $preq_no,
									'ExpectedDate' => date('Y-m-d'),
									'ShipmentID' => 1,
									'TermsPaymentID' => $get_vendor_code->TermsPaymentID,
									'FOBID' => 1,
									'CurrencyCode' => $Currency,
									'CurrencyRate' => $Rate,
									'BillingAddress' => $get_vendor_code->VendorAddress,
									'ShippingAddress' => $get_vendor_code->VendorAddress,
									'OldPOrdNumber' => $PONumber,
									'POrdDesc' => "Import ,PR,PO,Receive Item, $Desc, PO Tgl $PODate",
									'POrdSubTotal' => $Amount,
									'POrdDiscount' => 0,
									'POrdPPn10Pcnt' => $ppn_status,
									'POrdPPh22Pcnt' => 0,
									'POrdPPh23Pcnt' => 0,
									'POrdPPn10' => $TotalTax,
									'POrdPPh22' => 0,
									'POrdPPh23' => 0,
									'POrdEstFreight' => 0,
									'POrdTotalAmount' => ($Amount + $TotalTax),
									'POrdDPStatus' => 0,
									'POrdTotalDP' => 0,
									'POrdTaxesStatus' => $po_tax_status,
									'POrdInTaxStatus' => 0,
									'TransStatus' => 2,
									'AppLevel1Status' => 1,
									'AppLevel1Code' => $this->session->userdata("username"),
									'AppLevel1Date' => date("Y-m-d"),
									'AppLevel2Status' => 1,
									'AppLevel2Code' => $this->session->userdata("username"),
									'AppLevel2Date' => date("Y-m-d"),
									'CreatedBy' => $this->session->userdata("username"),
									'CreatedAt' => date('Y-m-d'),
									'LastUser' => $this->session->userdata("username")
								);
								
								$this->m_purchase_order->insert($data_po);
								
								$get_purchase_req = $this->m_import_transaction->get_purchase_req($preq_no, $ItemCode);
								
								$detail_data_po = array(
									'PReqDetailID' 	=> $get_purchase_req->PReqDetailID,
									'PReqNumber' 	=> $get_purchase_req->PReqNumber,
									'POrdNumber' 	=> $pord_number,
									'ItemCode' 		=> $ItemCode,
									'ItemDesc' 		=> $ItemDesc,
									'itemUnit' 		=> $ItemUnit,
									'itemQty' 		=> $Qty,
									'ItemQtyRI' 	=> $Qty,
									'ItemPrice' 	=> $UnitPrice,
									'ItemDisc' 		=> 0,
									'ItemAmount' 	=> $Amount,
									'ItemTaxPPn10' 	=> $TotalTax,
									'ItemTaxPPh22' 	=> 0,
									'ItemTaxPPh23' 	=> 0,
									'ItemTotalAmount' 	=> $Amount + $TotalTax,
									'ItemCategoryID' 	=> $ItemCategoryID,
									'ItemCategoryCode' 	=> $ItemCategoryCode,
									'ItemType'	 		=> $ItemType,
									'ItemStatus' 		=> $ItemStatus,
									'ItemPPh22Status' 	=> 0,
									'ItemPPh23Status' 	=> 0,
									'ItemAdvNetDueIn' 	=> 0,
									'ItemPriceNTax' 	=> $UnitPrice,
									'ItemCodeVendor' 	=> " ",
									'LastUser' 			=> $this->session->userdata("username")
								);
								$this->m_purchase_order->insert_detail($detail_data_po);
								$pordetail_id = $this->db->insert_id();
								
								//$get_receive_item = $this->m_import_transaction->get_receive_item($pord_number, $get_item_code->ItemCode);
								$data_update_ri = array(
									'POrdNumber' 	=> $pord_number
								);
								$this->m_receive_item->update($data_update_ri, $prec_no);
								
								$data_update_ri_detail = array(
									'POrdDetailID' 	=> $pordetail_id,
									'POrdNumber' 	=> $pord_number
								);
								$this->m_import_transaction->update_detail_item_code($data_update_ri_detail, $prec_no, $ItemCode);
							}
							else{
								$get_preq = $this->m_import_transaction->get_preq_num($Branch, $PONumber);
								$detail_data_preq_loop = array(
									'PReqNumber' 	=> $get_preq->PReqNumber,
									'ItemCode' 		=> $ItemCode,
									'ItemDesc' 		=> $ItemDesc,
									'itemUnit' 		=> $ItemUnit,
									'itemQty' 		=> $Qty,
									'ItemQtyPO' 	=> $Qty,
									'ItemQtyRI' 	=> $Qty,
									'ItemQtySpd' 	=> 0,
									'RequiredDate' => date('Y-m-d'),
									'ItemCategoryID' => $ItemCategoryID,
									'ItemCategoryCode' => $ItemCategoryCode,
									'ItemType' => $ItemType,
									'ItemStatus' => $ItemStatus,
									'ItemPPh22Status' => 0,
									'ItemPPh23Status' => 0,
									'ItemAdvNetDueIn' => 0,
									'LastUser' => $this->session->userdata("username")
								);
								$this->m_purchase_requisition->insert_detail($detail_data_preq_loop);
								
								$get_purchase_req 	= $this->m_import_transaction->get_purchase_req($get_preq->PReqNumber, $ItemCode);
								$get_pord_no 		= $this->m_import_transaction->get_po_num($Branch, $PONumber);
								
								$detail_data_po = array(
									'PReqDetailID' 	=> $get_purchase_req->PReqDetailID,
									'PReqNumber' 	=> $get_purchase_req->PReqNumber,
									'POrdNumber' 	=> $get_pord_no->POrdNumber,
									'ItemCode' 		=> $ItemCode,
									'ItemDesc' 		=> $ItemDesc,
									'itemUnit' 		=> $ItemUnit,
									'itemQty' 		=> $Qty,
									'ItemQtyRI' 	=> $Qty,
									'ItemPrice' 	=> $UnitPrice,
									'ItemDisc' 		=> 0,
									'ItemAmount' 	=> $Amount,
									'ItemTaxPPn10' 	=> $TotalTax,
									'ItemTaxPPh22' 	=> 0,
									'ItemTaxPPh23' 	=> 0,
									'ItemTotalAmount' 	=> $Amount + $TotalTax,
									'ItemCategoryID' 	=> $ItemCategoryID,
									'ItemCategoryCode' 	=> $ItemCategoryCode,
									'ItemType'	 		=> $ItemType,
									'ItemStatus' 		=> $ItemStatus,
									'ItemPPh22Status' 	=> 0,
									'ItemPPh23Status' 	=> 0,
									'ItemAdvNetDueIn' 	=> 0,
									'ItemPriceNTax' 	=> $UnitPrice,
									'ItemCodeVendor' 	=> " ",
									'LastUser' 			=> $this->session->userdata("username")
								);
								$this->m_purchase_order->insert_detail($detail_data_po);
								$pordetail_id = $this->db->insert_id();
								
								$data_update_ri = array(
									'POrdNumber' 	=> $pord_number
								);
								$this->m_receive_item->update($data_update_ri, $prec_no);
								
								$data_update_ri_detail = array(
									'POrdDetailID' 	=> $pordetail_id,
									'POrdNumber' 	=> $pord_number
								);
								$this->m_import_transaction->update_detail_item_code($data_update_ri_detail, $prec_no, $ItemCode);
								
								$data_update_po = array(
									'POrdSubTotal' => $get_pord_no->POrdSubTotal + $Amount,
									'POrdPPn10' => $get_pord_no->POrdPPn10 + $TotalTax,
									'POrdPPn10Pcnt' => $ppn_status,
									'POrdTaxesStatus' => $po_tax_status,
									'POrdTotalAmount' => $get_pord_no->POrdTotalAmount + ($Amount + $TotalTax)
								);
								$this->m_purchase_order->update($data_update_po, $get_pord_no->POrdNumber);
							}
							$PONumber_loop = $PONumber;
							
						}
						else{
							//$get_receive_item = $this->m_import_transaction->get_receive_item($pord_number, $get_item_code->ItemCode);
							$get_receive_no 		= $this->m_import_transaction->get_ri_num($Branch, $ReceiptNo);
							
							$detail_data = array(
								'PRecNumber' 	=> $get_receive_no->PRecNumber,
								'ItemCode' 		=> $ItemCode,
								'ItemDesc' 		=> $ItemDesc,
								'itemUnit' 		=> $ItemUnit,
								'itemQty' 		=> $Qty,
								'ItemDisc' 		=> 0,
								'ItemPrice' 	=> $UnitPrice,
								'ItemAmount' 	=> $Amount,
								'ItemTaxPPn10' 		=> $TotalTax,
								'ItemTotalAmount' 	=> $Amount + $TotalTax,
								'ItemCategoryID' 	=> $ItemCategoryID,
								'ItemCategoryCode' 	=> $ItemCategoryCode,
								'ItemType'	 		=> $ItemType,
								'ItemStatus' 		=> $ItemStatus,
								'ItemCodeVendor' 	=> " ",
								'LastUser' 			=> $this->session->userdata("username")
							);
							$this->m_receive_item->insert_detail($detail_data);
							
							$data_update_ri = array(
								'PRecSubTotal' => $get_receive_no->PRecSubTotal + $Amount,
								'PRecPPn10Pcnt' => $ppn_status,
								'PRecPPn10' => $get_receive_no->PRecPPn10 + $TotalTax,
								'PRecTotalAmount' => $get_receive_no->PRecTotalAmount + ($Amount + $TotalTax),
								'PRecTaxesStatus' => $po_tax_status
							);
							$this->m_receive_item->update($data_update_ri, $get_receive_no->PRecNumber);
							
							if($PONumber_loop != $PONumber){
								/*
									Purchase Req
								*/
								$data_preq = array(
									'BranchCode' 		=> $Branch,
									'DepartmentCode' 	=> $this->session->userdata('department'),
									'PReqDate' 			=> date('Y-m-d'),
									'PReqNumber' 		=> $preq_no,
									'AppLevel1Status' 	=> 1,
									'PReqDesc' 			=> "Import ,PR,PO,Receive Item, $Desc, PO Tgl $PODate",
									'AppLevel1Code' 	=> $this->session->userdata("username"),
									'AppLevel1Date' 	=> date("Y-m-d"),
									'TransStatus' 		=> 2,
									'CreatedBy' 		=> $this->session->userdata("username"),
									'CreatedAt' 		=> date('Y-m-d'),
									'OldPReqNumber' 	=> $PONumber,
									'LastUser' 			=> $this->session->userdata("username")
								);
								$this->m_purchase_requisition->insert($data_preq);
								
								$detail_data_preq = array(
									'PReqNumber' => $preq_no,
									'ItemCode' => $ItemCode,
									'ItemDesc' => $ItemDesc,
									'itemUnit' => $ItemUnit,
									'itemQty' => $Qty,
									'ItemQtyPO' => $Qty,
									'ItemQtyRI' => $Qty,
									'ItemQtySpd' => 0,
									'RequiredDate' => date('Y-m-d'),
									'ItemCategoryID' => $ItemCategoryID,
									'ItemCategoryCode' => $ItemCategoryCode,
									'ItemType' => $ItemType,
									'ItemStatus' => $ItemStatus,
									'ItemPPh22Status' => 0,
									'ItemPPh23Status' => 0,
									'ItemAdvNetDueIn' => 0,
									'LastUser' => $this->session->userdata("username")
								);
								$this->m_purchase_requisition->insert_detail($detail_data_preq);
								/*============================End===========================================*/
								
								$data_po = array(
									'BranchCode' => $Branch,
									'VendorCode' => $get_vendor_code->VendorCode,
									'POrdDate' => date('Y-m-d'),
									'POrdNumber' => $pord_number,
									'PReqDate' => date('Y-m-d'),
									'PReqNumber' => $preq_no,
									'ExpectedDate' => date('Y-m-d'),
									'ShipmentID' => 1,
									'TermsPaymentID' => $get_vendor_code->TermsPaymentID,
									'FOBID' => 1,
									'CurrencyCode' => $Currency,
									'CurrencyRate' => $Rate,
									'BillingAddress' => $get_vendor_code->VendorAddress,
									'ShippingAddress' => $get_vendor_code->VendorAddress,
									'OldPOrdNumber' => $PONumber,
									'POrdDesc' => "Import ,PR,PO,Receive Item, $Desc, PO Tgl $PODate",
									'POrdSubTotal' => $Amount,
									'POrdDiscount' => 0,
									'POrdPPn10Pcnt' => $ppn_status,
									'POrdPPh22Pcnt' => 0,
									'POrdPPh23Pcnt' => 0,
									'POrdPPn10' => $TotalTax,
									'POrdPPh22' => 0,
									'POrdPPh23' => 0,
									'POrdEstFreight' => 0,
									'POrdTotalAmount' => ($Amount + $TotalTax),
									'POrdDPStatus' => 0,
									'POrdTotalDP' => 0,
									'POrdTaxesStatus' => $po_tax_status,
									'POrdInTaxStatus' => 0,
									'TransStatus' => 2,
									'AppLevel1Status' => 1,
									'AppLevel1Code' => $this->session->userdata("username"),
									'AppLevel1Date' => date("Y-m-d"),
									'AppLevel2Status' => 1,
									'AppLevel2Code' => $this->session->userdata("username"),
									'AppLevel2Date' => date("Y-m-d"),
									'CreatedBy' => $this->session->userdata("username"),
									'CreatedAt' => date('Y-m-d'),
									'LastUser' => $this->session->userdata("username")
								);
								
								$this->m_purchase_order->insert($data_po);
								
								$get_purchase_req = $this->m_import_transaction->get_purchase_req($preq_no, $ItemCode);
								
								$detail_data_po = array(
									'PReqDetailID' 	=> $get_purchase_req->PReqDetailID,
									'PReqNumber' 	=> $get_purchase_req->PReqNumber,
									'POrdNumber' 	=> $pord_number,
									'ItemCode' 		=> $ItemCode,
									'ItemDesc' 		=> $ItemDesc,
									'itemUnit' 		=> $ItemUnit,
									'itemQty' 		=> $Qty,
									'ItemQtyRI' 	=> $Qty,
									'ItemPrice' 	=> $UnitPrice,
									'ItemDisc' 		=> 0,
									'ItemAmount' 	=> $Amount,
									'ItemTaxPPn10' 	=> $TotalTax,
									'ItemTaxPPh22' 	=> 0,
									'ItemTaxPPh23' 	=> 0,
									'ItemTotalAmount' 	=> $Amount + $TotalTax,
									'ItemCategoryID' 	=> $ItemCategoryID,
									'ItemCategoryCode' 	=> $ItemCategoryCode,
									'ItemType'	 		=> $ItemType,
									'ItemStatus' 		=> $ItemStatus,
									'ItemPPh22Status' 	=> 0,
									'ItemPPh23Status' 	=> 0,
									'ItemAdvNetDueIn' 	=> 0,
									'ItemPriceNTax' 	=> $UnitPrice,
									'ItemCodeVendor' 	=> " ",
									'LastUser' 			=> $this->session->userdata("username")
								);
								$this->m_purchase_order->insert_detail($detail_data_po);
								$pordetail_id = $this->db->insert_id();
								
								$data_update_ri = array(
									'POrdNumber' 	=> $pord_number
								);
								$this->m_receive_item->update($data_update_ri, $get_receive_no->PRecNumber);
								
								$data_update_ri_detail = array(
									'POrdDetailID' 	=> $pordetail_id,
									'POrdNumber' 	=> $pord_number
								);
								$this->m_import_transaction->update_detail_item_code($data_update_ri_detail, $get_receive_no->PRecNumber, $ItemCode);
							}
							else{
								$get_preq = $this->m_import_transaction->get_preq_num($Branch, $PONumber);
								$detail_data_preq_loop = array(
									'PReqNumber' 	=> $get_preq->PReqNumber,
									'ItemCode' 		=> $ItemCode,
									'ItemDesc' 		=> $ItemDesc,
									'itemUnit' 		=> $ItemUnit,
									'itemQty' 		=> $Qty,
									'ItemQtyPO' 	=> $Qty,
									'ItemQtyRI' 	=> $Qty,
									'ItemQtySpd' 	=> 0,
									'RequiredDate' => date('Y-m-d'),
									'ItemCategoryID' => $ItemCategoryID,
									'ItemCategoryCode' => $ItemCategoryCode,
									'ItemType' => $ItemType,
									'ItemStatus' => $ItemStatus,
									'ItemPPh22Status' => 0,
									'ItemPPh23Status' => 0,
									'ItemAdvNetDueIn' => 0,
									'LastUser' => $this->session->userdata("username")
								);
								$this->m_purchase_requisition->insert_detail($detail_data_preq_loop);
								
								$get_purchase_req 	= $this->m_import_transaction->get_purchase_req($get_preq->PReqNumber, $ItemCode);
								$get_pord_no 		= $this->m_import_transaction->get_po_num($Branch, $PONumber);
								
								$detail_data_po = array(
									'PReqDetailID' 	=> $get_purchase_req->PReqDetailID,
									'PReqNumber' 	=> $get_purchase_req->PReqNumber,
									'POrdNumber' 	=> $get_pord_no->POrdNumber,
									'ItemCode' 		=> $ItemCode,
									'ItemDesc' 		=> $ItemDesc,
									'itemUnit' 		=> $ItemUnit,
									'itemQty' 		=> $Qty,
									'ItemQtyRI' 	=> $Qty,
									'ItemPrice' 	=> $UnitPrice,
									'ItemDisc' 		=> 0,
									'ItemAmount' 	=> $Amount,
									'ItemTaxPPn10' 	=> $TotalTax,
									'ItemTaxPPh22' 	=> 0,
									'ItemTaxPPh23' 	=> 0,
									'ItemTotalAmount' 	=> $Amount + $TotalTax,
									'ItemCategoryID' 	=> $ItemCategoryID,
									'ItemCategoryCode' 	=> $ItemCategoryCode,
									'ItemType'	 		=> $ItemType,
									'ItemStatus' 		=> $ItemStatus,
									'ItemPPh22Status' 	=> 0,
									'ItemPPh23Status' 	=> 0,
									'ItemAdvNetDueIn' 	=> 0,
									'ItemPriceNTax' 	=> $UnitPrice,
									'ItemCodeVendor' 	=> " ",
									'LastUser' 			=> $this->session->userdata("username")
								);
								$this->m_purchase_order->insert_detail($detail_data_po);
								$pordetail_id = $this->db->insert_id();
								
								$data_update_ri = array(
									'POrdNumber' 	=> $pord_number
								);
								$this->m_receive_item->update($data_update_ri, $get_receive_no->PRecNumber);
								
								$data_update_ri_detail = array(
									'POrdDetailID' 	=> $pordetail_id,
									'POrdNumber' 	=> $pord_number
								);
								$this->m_import_transaction->update_detail_item_code($data_update_ri_detail, $get_receive_no->PRecNumber, $ItemCode);
								
								$data_update_po = array(
									'POrdSubTotal' => $get_pord_no->POrdSubTotal + $Amount,
									'POrdPPn10' => $get_pord_no->POrdPPn10 + $TotalTax,
									'POrdPPn10Pcnt' => $ppn_status,
									'POrdTaxesStatus' => $po_tax_status,
									'POrdTotalAmount' => $get_pord_no->POrdTotalAmount + ($Amount + $TotalTax)
								);
								$this->m_purchase_order->update($data_update_po, $get_pord_no->POrdNumber);
							}
							$PONumber_loop = $PONumber;
						}
						$Receipt_no_loop = $ReceiptNo;
						
						@$TotalAmount[$ReceiptNo] += ($Amount);
						@$Branch_Code = $Branch;
					}
				}
				
				/*======================================Loop Journal RI======*/
				foreach ($TotalAmount as $key => $value) {
					$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
					$HutangAccount = $this->m_account_journal->get_sys_item_account('Unbilled');
					$get_receive_no_journal 		= $this->m_import_transaction->get_ri_num($Branch_Code, $key);
					if($OpeningBalance == false) {
						throw new Exception('Journal Opening Balance belum tersedia di COA silahkan lihat kembali COA');
					}
					else if($HutangAccount == false) {
						throw new Exception('Journal Hutang yang belum ditagih belum tersedia di Preference silahkan lihat kembali Preference');
					}
					else{
						$journal_debet = array(
							'PRecDate' => date("Y-m-d"),
							'PRecNumber' => $get_receive_no_journal->PRecNumber,
							'PRecDesc' => "Import Receive Item",
							'PRecAccountNumber' => $OpeningBalance->AccountNumber,
							'PRecSaldoDebet' => $Currency == 'IDR' ? $value : doubleval($value) * $Rate,
							'PRecSaldoCredit' => 0,
							'AmountCurrency' => $value,
							'PRecSignStatus' => 1,
							'LastUser' => $this->session->userdata("username")
						);
			
						$this->m_receive_item->insert_journal($journal_debet);
						
						$journal_kredit = array(
							'PRecDate' => date("Y-m-d"),
							'PRecNumber' => $get_receive_no_journal->PRecNumber,
							'PRecDesc' => "Import Receive Item",
							'PRecAccountNumber' => $HutangAccount->AccountNumber,
							'PRecSaldoDebet' => 0,
							'PRecSaldoCredit' => $Currency == 'IDR' ? $value : doubleval($value) * $Rate,
							'AmountCurrency' => $value,
							'PRecSignStatus' => 0,
							'LastUser' => $this->session->userdata("username")
						);
						
						$this->m_receive_item->insert_journal($journal_kredit);
						
						$data_hisimport_detail = array(
							'ImportTransID'     => $num,
							'SourceNumber'      => $get_receive_no_journal->PRecNumber,
							'TransType'         => $TransType, 
							'SourceDate'        => $sourceDate,
							'BranchCode'        => $Branch,
							'ImportNumber'      => $number_data,
							'LastUser'          => $this->session->userdata('username')
						);	
						$this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
						
						$data_app_finish_ri = array(
							'AppFinished' => 1
						);
						$this->m_receive_item->update($data_app_finish_ri, $get_receive_no_journal->PRecNumber);
					}
				}
				/*==========END=======*/
				
				/* =============================trans roll back dan trans commit============================/ */
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$result['status']   = true;
					$result['message']  = get_notification('insert', 0);
				} else {
					$this->db->trans_commit();
					$result['status']   = false;
					$result['message']  = get_notification('insert', 1);
				}
				/* ==================================end====================================================== */
				echo json_encode($result);
			}
		 }
		 
		 catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
			$this->db->trans_rollback();
            echo json_encode($result);
        }
	}
	
	public function import_item(){
        try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];

            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
                $objWriter      = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount     = $objPHPExcel->getSheetCount();

                //================ RULE BARU ==============================//
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();

                if( notCaseSensitifNotSpace($sheetData[1]['A'])==notCaseSensitifNotSpace("Item No.") && //pengecekkan header huruf tidak case sensitif dan spasi tidak dipermasalahkan, jd saat pengecekkan menghilangkan spasi serta huruf dipaksa sama jenisnya(Upper/lower),yg dipakai sekarang upper. ini function diambil dari helper customstring_helper.php
                    notCaseSensitifNotSpace($sheetData[1]['B'])==notCaseSensitifNotSpace("Item Description") &&
                    notCaseSensitifNotSpace($sheetData[1]['D'])==notCaseSensitifNotSpace("Unit 1") &&
                    notCaseSensitifNotSpace($sheetData[1]['G'])==notCaseSensitifNotSpace("Item Type") &&
                    notCaseSensitifNotSpace($sheetData[1]['H'])==notCaseSensitifNotSpace("Merk") &&
                    notCaseSensitifNotSpace($sheetData[1]['I'])==notCaseSensitifNotSpace("Design") &&
                    notCaseSensitifNotSpace($sheetData[1]['J'])==notCaseSensitifNotSpace("Colour") &&
                    notCaseSensitifNotSpace($sheetData[1]['K'])==notCaseSensitifNotSpace("Size") &&
                    notCaseSensitifNotSpace($sheetData[1]['L'])==notCaseSensitifNotSpace("Quality") &&
                    notCaseSensitifNotSpace($sheetData[1]['M'])==notCaseSensitifNotSpace("Type") &&
                    notCaseSensitifNotSpace($sheetData[1]['N'])==notCaseSensitifNotSpace("Shading") &&
                    notCaseSensitifNotSpace($sheetData[1]['O'])==notCaseSensitifNotSpace("Group") &&
                    notCaseSensitifNotSpace($sheetData[1]['X'])==notCaseSensitifNotSpace("Item Category Name")    
                ){         
                    $dataImport = [];
                    $dataImport['data_hisimport']       = [];
                    $dataImport['data_hisimport_detail']= [];
                    $dataImport['data_item']            = [];
                    $dataImport['data_detail']          = [];
                    $tempArrayItemCode                  = [];

                    $sourceDate     = date('Y-m-d');
                    $TransType      = 'Item';
                    $DataType       = 'Insert';
                    $status         = 1;		
                    $num            = $this->m_import_transaction->num_importtrans();
                    $number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
                    $data_hisimport = array(
                        'ImportTransID' => $num,
                        'TransType' 	=> $TransType, 
                        'DataType'      => $DataType, 
                        'ImportStatus' 	=> $status,
                        'LastEdited' 	=> date('Y-m-d'),
                        'LastUser'      => $this->session->userdata('username')
                    );
                    $dataImport['data_hisimport'][] = $data_hisimport;

                    for($i=2; $i<=$lastRow; $i++){
                        $ItemCode           = upperNotSpace($sheetData[$i]['A']);
                        $ItemDesc           = $sheetData[$i]['B'];
                        $ItemUnit           = $sheetData[$i]['D'];
                        $ItemTypeID         = $sheetData[$i]['G'];
                        $ItemMerk           = $sheetData[$i]['H'];
                        $ItemDesign         = $sheetData[$i]['I'];
                        $ItemColour         = $sheetData[$i]['J'];
                        $ItemSize           = $sheetData[$i]['K'];
                        $ItemQuality        = $sheetData[$i]['L'];
                        $ItemType           = $sheetData[$i]['M'];
                        $ItemShading        = $sheetData[$i]['N'];
                        $ItemGroup          = $sheetData[$i]['O'];
                        $ItemCategoryID     = $sheetData[$i]['X'];

                        $ItemCategoryID_Trouper = strtoupper($ItemCategoryID);
                        $get_item_code          = $this->m_import_transaction->get_item_code($ItemCode);
                        $get_item_type          = $this->m_import_transaction->get_item_type($ItemTypeID);
                        $get_item_kategori      = $this->m_import_transaction->get_item_kategori($ItemCategoryID_Trouper);

                        if( ($ItemCode==null || $ItemCode=="") &&
                            (notCaseSensitifNotSpace($ItemDesc)==null || notCaseSensitifNotSpace($ItemDesc)=="") &&
                            (empty($ItemTypeID)) && (empty($ItemCategoryID)) ){//cek jika itemCode & $ItemDesc & $ItemTypeID & $ItemCategoryID kosong                        
                            //SKIP
                        }else if($ItemCode==null || $ItemCode==""){//cek jika item kosong                          
                            throw new Exception(noticesImport("denied", ["column"=>"Item No.","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(notCaseSensitifNotSpace($ItemDesc)==null || notCaseSensitifNotSpace($ItemDesc)==""){//cek jika item type kosong                        
                            throw new Exception(noticesImport("denied", ["column"=>"Item Description","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(empty($ItemTypeID)){//cek jika item type kosong                        
                            throw new Exception(noticesImport("denied", ["column"=>"Item Type","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(empty($ItemCategoryID)){//cek jika item kategory kosong                            
                            throw new Exception(noticesImport("denied", ["column"=>"Item Kategori","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(empty($get_item_kategori->ItemCategoryName)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Item Kategori","code"=>$ItemCategoryID,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(in_array($ItemCode, $tempArrayItemCode)){//ini utk pengecekkan klo di data itemcode yg akan dimasukkan ga blh sudah ada di table item
                            throw new Exception(noticesImport("duplicate", ["column"=>"Item No.","code"=>$ItemCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(!empty($get_item_code->ItemCode)){//ini utk pengecekkan klo di data itemcode yg akan dimasukkan ga blh sudah ada di table item
                            throw new Exception(noticesImport("sameInTable", ["column"=>"Item No.","code"=>$ItemCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else{
                            $tempArrayItemCode[]= $ItemCode;//temporary data item code
                            $sourceDate         = date('Y-m-d');
                            /*=============Penomeran item code by initial ===============*/
                            $dataitemcategori 	= $this->m_import_transaction->create_initial_code_by_name($ItemCategoryID_Trouper);
                            $New_Item_code      = $get_item_kategori->InitialCategory.'-'.$dataitemcategori;
                            /*=============END Penomeran item code by initial ===============*/
                            $data_item = array(
                                'ItemCode'          => $ItemCode,
                                'ItemTypeID'        => $get_item_type->ItemTypeID,
                                'ItemUnit'          => $ItemUnit,
                                'ItemDesc'          => $ItemDesc,
                                'ItemCategoryID'    => $get_item_kategori->ItemCategoryID,
                                'AppLevel1Status'   => 1,
                                'AppLevel1Code'     => $this->session->userdata('username'),
                                'AppLevel1Date'     => date('Y-m-d'),
                                'AppLevel2Status'   => 1,
                                'AppLevel2Code'     => $this->session->userdata('username'),
                                'AppLevel2Date'     => date('Y-m-d'),
                                'TransStatus'       => 1,
                                'ItemPPhType'       => 0,
                                'LastUser'          => $this->session->userdata('username')
                            );
                            $dataImport['data_item'][] = $data_item;

                            $data_detail = array(
                                'ItemCode'      => $ItemCode,
                                'ItemMerk'      => $ItemMerk,
                                'ItemDesign' 	=> $ItemDesign,
                                'ItemColour' 	=> $ItemColour,
                                'ItemSize'      => $ItemSize,
                                'ItemQuality' 	=> $ItemQuality,
                                'ItemType'      => $ItemType,
                                'ItemShading' 	=> $ItemShading,
                                'ItemGroup' 	=> $ItemGroup,
                                'LastUser'      => $this->session->userdata('username')
                            );
                            $dataImport['data_detail'][] = $data_detail;

                            $data_hisimport_detail = array(
                                'ImportTransID'     => $num,
                                'SourceNumber'      => $ItemCode,
                                'TransType'         => $TransType, 
                                'SourceDate'        => $sourceDate,
                                'ImportNumber'      => $number_data,
                                'LastUser'          => $this->session->userdata('username')
                            );	
                            $dataImport['data_hisimport_detail'][] = $data_hisimport_detail;                            
                        }
                    }

                    $rstImport = $this->m_import_transaction->importItemMaster($dataImport);
                    if($rstImport){
                        $result['status']   = true;
                        $result['message']  = get_notification('insert', 1);
                        //$result['message']  = noticesImport("success",[]);
                    }else{
                        $result['status']   = false;
                        $result['message']  = get_notification('insert', 0);
                        //$result['message']  = noticesImport("failed",[]);
                    }
                    echo json_encode($result);
                }else{                    
                    throw new Exception(noticesImport("header",[]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }
                //================END RULE BARU ==============================//
            }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);
        }
    }

    public function import_item_fromBPI(){
        try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];

            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
                $objWriter      = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount     = $objPHPExcel->getSheetCount();

                //================ RULE BARU ==============================//
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();

                if( notCaseSensitifNotSpace($sheetData[1]['A'])==notCaseSensitifNotSpace("Item No.") && //pengecekkan header huruf tidak case sensitif dan spasi tidak dipermasalahkan, jd saat pengecekkan menghilangkan spasi serta huruf dipaksa sama jenisnya(Upper/lower),yg dipakai sekarang upper. ini function diambil dari helper customstring_helper.php
                    notCaseSensitifNotSpace($sheetData[1]['B'])==notCaseSensitifNotSpace("Item Description") &&
                    notCaseSensitifNotSpace($sheetData[1]['D'])==notCaseSensitifNotSpace("Unit 1") &&
                    notCaseSensitifNotSpace($sheetData[1]['G'])==notCaseSensitifNotSpace("Item Type") &&
                    notCaseSensitifNotSpace($sheetData[1]['H'])==notCaseSensitifNotSpace("Merk") &&
                    notCaseSensitifNotSpace($sheetData[1]['I'])==notCaseSensitifNotSpace("Design") &&
                    notCaseSensitifNotSpace($sheetData[1]['J'])==notCaseSensitifNotSpace("Colour") &&
                    notCaseSensitifNotSpace($sheetData[1]['K'])==notCaseSensitifNotSpace("Size") &&
                    notCaseSensitifNotSpace($sheetData[1]['L'])==notCaseSensitifNotSpace("Quality") &&
                    notCaseSensitifNotSpace($sheetData[1]['M'])==notCaseSensitifNotSpace("Type") &&
                    notCaseSensitifNotSpace($sheetData[1]['N'])==notCaseSensitifNotSpace("Shading") &&
                    notCaseSensitifNotSpace($sheetData[1]['O'])==notCaseSensitifNotSpace("Group") &&
                    notCaseSensitifNotSpace($sheetData[1]['X'])==notCaseSensitifNotSpace("Item Category Name")    
                ){         
                    $dataImport = [];
                    $dataImport['data_hisimport']       = [];
                    $dataImport['data_hisimport_detail']= [];
                    $dataImport['data_item']            = [];
                    $dataImport['data_detail']          = [];
                    $tempArrayItemCode                  = [];

                    $sourceDate     = date('Y-m-d');
                    $TransType      = 'Item';
                    $DataType       = 'Insert';
                    $status         = 1;		
                    $num            = $this->m_import_transaction->num_importtrans();
                    $number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
                    $data_hisimport = array(
                        'ImportTransID' => $num,
                        'TransType' 	=> $TransType, 
                        'DataType'      => $DataType, 
                        'ImportStatus' 	=> $status,
                        'LastEdited' 	=> date('Y-m-d'),
                        'LastUser'      => $this->session->userdata('username')
                    );
                    $this->m_import_transaction->insert_history_transaction($data_hisimport);
                    //$dataImport['data_hisimport'][] = $data_hisimport;

                    for($i=2; $i<=$lastRow; $i++){
                        $ItemCode           = upperNotSpace($sheetData[$i]['A']);
                        $ItemDesc           = $sheetData[$i]['B'];
                        $ItemUnit           = $sheetData[$i]['D'];
                        $ItemTypeID         = $sheetData[$i]['G'];
                        $ItemMerk           = $sheetData[$i]['H'];
                        $ItemDesign         = $sheetData[$i]['I'];
                        $ItemColour         = $sheetData[$i]['J'];
                        $ItemSize           = $sheetData[$i]['K'];
                        $ItemQuality        = $sheetData[$i]['L'];
                        $ItemType           = $sheetData[$i]['M'];
                        $ItemShading        = $sheetData[$i]['N'];
                        $ItemGroup          = $sheetData[$i]['O'];
                        $ItemCategoryID     = $sheetData[$i]['X'];

                        $ItemCategoryID_Trouper = strtoupper($ItemCategoryID);
                        $get_item_code          = $this->m_import_transaction->get_item_code($ItemCode);
                        $get_item_type          = $this->m_import_transaction->get_item_type($ItemTypeID);
                        $get_item_kategori      = $this->m_import_transaction->get_item_kategori($ItemCategoryID_Trouper);

                        if( (notCaseSensitifNotSpace($ItemDesc)==null || notCaseSensitifNotSpace($ItemDesc)=="") &&
                            (empty($ItemTypeID)) && (empty($ItemCategoryID)) ){//cek jika itemCode & $ItemDesc & $ItemTypeID & $ItemCategoryID kosong                        
                            //SKIP
                        }else if(notCaseSensitifNotSpace($ItemDesc)==null || notCaseSensitifNotSpace($ItemDesc)==""){//cek jika item type kosong                        
                            throw new Exception(noticesImport("denied", ["column"=>"Item Description","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(empty($ItemTypeID)){//cek jika item type kosong                        
                            throw new Exception(noticesImport("denied", ["column"=>"Item Type","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(empty($ItemCategoryID)){//cek jika item kategory kosong                            
                            throw new Exception(noticesImport("denied", ["column"=>"Item Kategori","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(empty($get_item_kategori->ItemCategoryName)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Item Kategori","code"=>$ItemCategoryID,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(in_array($ItemCode, $tempArrayItemCode)){//ini utk pengecekkan klo di data itemcode yg akan dimasukkan ga blh sudah ada di table item
                            throw new Exception(noticesImport("duplicate", ["column"=>"Item No.","code"=>$ItemCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if(!empty($get_item_code->ItemCode)){//ini utk pengecekkan klo di data itemcode yg akan dimasukkan ga blh sudah ada di table item
                            throw new Exception(noticesImport("sameInTable", ["column"=>"Item No.","code"=>$ItemCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else{
                            $tempArrayItemCode[]= $ItemCode;//temporary data item code
                            $sourceDate         = date('Y-m-d');
                            /*=============Penomeran item code by initial ===============*/
                            $dataitemcategori 	= $this->m_import_transaction->create_initial_code_by_name($get_item_kategori->ItemCategoryID);
                            //echo $this->db->last_query().'<br>';

                            //echo $dataitemcategori;
                            $New_Item_code      = $get_item_kategori->InitialCategory.'-'.($dataitemcategori);
                            /*=============END Penomeran item code by initial ===============*/
                            
                            $data_item = array(
                                'ItemCode'          => $New_Item_code,
                                'ItemTypeID'        => $get_item_type->ItemTypeID,
                                'ItemUnit'          => $ItemUnit,
                                'ItemDesc'          => $ItemDesc,
                                'ItemCategoryID'    => $get_item_kategori->ItemCategoryID,
                                'AppLevel1Status'   => 1,
                                'AppLevel1Code'     => $this->session->userdata('username'),
                                'AppLevel1Date'     => date('Y-m-d'),
                                'AppLevel2Status'   => 1,
                                'AppLevel2Code'     => $this->session->userdata('username'),
                                'AppLevel2Date'     => date('Y-m-d'),
                                'TransStatus'       => 1,
                                'ItemPPhType'       => 0,
                                'LastUser'          => $this->session->userdata('username')
                            );
                            $this->m_import_transaction->insert_am_item($data_item);
                            //$dataImport['data_item'][] = $data_item;

                            $data_detail = array(
                                'ItemCode'      => $New_Item_code,
                                'ItemMerk'      => $ItemMerk,
                                'ItemDesign' 	=> $ItemDesign,
                                'ItemColour' 	=> $ItemColour,
                                'ItemSize'      => $ItemSize,
                                'ItemQuality' 	=> $ItemQuality,
                                'ItemType'      => $ItemType,
                                'ItemShading' 	=> $ItemShading,
                                'ItemGroup' 	=> $ItemGroup,
                                'LastUser'      => $this->session->userdata('username')
                            );
                            $this->m_import_transaction->insert_am_item_detail($data_detail);
                            //$dataImport['data_detail'][] = $data_detail;

                            $data_hisimport_detail = array(
                                'ImportTransID'     => $num,
                                'SourceNumber'      => $New_Item_code,
                                'TransType'         => $TransType, 
                                'SourceDate'        => $sourceDate,
                                'ImportNumber'      => $number_data,
                                'LastUser'          => $this->session->userdata('username')
                            );	
                            $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
                            //$dataImport['data_hisimport_detail'][] = $data_hisimport_detail;                            
                        }
                    }

                    //$rstImport = "";//$this->m_import_transaction->importItemMaster($dataImport);
                    $result['status']   = true;
                        $result['message']  = get_notification('insert', 1);
                    echo json_encode($result);
                }else{                    
                    throw new Exception(noticesImport("header",[]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }
                //================END RULE BARU ==============================//
            }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);
        }
    }

	public function import_expense(){
		try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];

            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
                $objWriter      = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount     = $objPHPExcel->getSheetCount();

                //================ RULE BARU ==============================//
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				
				if(notCaseSensitifNotSpace($sheetData[1]['A'])!=notCaseSensitifNotSpace("Item No.")){
					throw new Exception("Maaf transaksi upload gagal Header Item No. tidak berada di kolom [A] silahkan periksa kembali");//pesan yang diambil dr helper : notices_import_file_helper.php
				}
				else if(notCaseSensitifNotSpace($sheetData[1]['B'])!=notCaseSensitifNotSpace("Item Description")){
					throw new Exception("Maaf transaksi upload gagal Header Item Description tidak berada di kolom [B] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[1]['X'])!=notCaseSensitifNotSpace("Item Category Name")){
					throw new Exception("Maaf transaksi upload gagal Header Item Category Name tidak di kolom [X] silahkan periksa kembali");
				}
							
				$dataImport = [];
				$dataImport['data_hisimport']       = [];
				$dataImport['data_hisimport_detail']= [];
				$dataImport['data_item']            = [];
				$dataImport['data_detail']          = [];
				$tempArrayItemCode                  = [];

				$sourceDate     = date('Y-m-d');
				$TransType      = 'Item_Expense';
				$DataType       = 'Insert';
				$status         = 1;		
				$num            = $this->m_import_transaction->num_importtrans();
				$number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
				$data_hisimport = array(
					'ImportTransID' => $num,
					'TransType' 	=> $TransType, 
					'DataType'      => $DataType, 
					'ImportStatus' 	=> $status,
					'LastEdited' 	=> date('Y-m-d'),
					'LastUser'      => $this->session->userdata('username')
				);
				$dataImport['data_hisimport'][] = $data_hisimport;
				
				for($i=2; $i<=$lastRow; $i++){
					$ItemCode           = upperNotSpace($sheetData[$i]['A']);
					$ItemDesc           = $sheetData[$i]['B'];
					$ItemUnit           = $sheetData[$i]['D'];
					$ItemTypeID         = $sheetData[$i]['G'];
					$ItemMerk           = $sheetData[$i]['H'];
					$ItemDesign         = $sheetData[$i]['I'];
					$ItemColour         = $sheetData[$i]['J'];
					$ItemSize           = $sheetData[$i]['K'];
					$ItemQuality        = $sheetData[$i]['L'];
					$ItemType           = $sheetData[$i]['M'];
					$ItemShading        = $sheetData[$i]['N'];
					$ItemGroup          = $sheetData[$i]['O'];
					$ItemCategoryID     = $sheetData[$i]['X'];

					$ItemCategoryID_Trouper = strtoupper($ItemCategoryID);
					$get_item_code          = $this->m_import_transaction->get_item_code($ItemCode);
					$get_item_type          = $this->m_import_transaction->get_item_type($ItemTypeID);
					$get_item_kategori      = $this->m_import_transaction->get_item_kategori_expense($ItemCategoryID_Trouper);
					

					if( ($ItemCode==null || $ItemCode=="") &&
						(notCaseSensitifNotSpace($ItemDesc)==null || notCaseSensitifNotSpace($ItemDesc)=="") &&
						(empty($ItemTypeID)) && (empty($ItemCategoryID)) ){//cek jika itemCode & $ItemDesc & $ItemTypeID & $ItemCategoryID kosong                        
						//SKIP
					}else if($ItemCode==null || $ItemCode==""){//cek jika item kosong                          
						throw new Exception(noticesImport("denied", ["column"=>"Item No.","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
					}else if(notCaseSensitifNotSpace($ItemDesc)==null || notCaseSensitifNotSpace($ItemDesc)==""){//cek jika item type kosong                        
						throw new Exception(noticesImport("denied", ["column"=>"Item Description","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
					}else if(empty($ItemTypeID)){//cek jika item type kosong                        
						throw new Exception(noticesImport("denied", ["column"=>"Item Type","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
					}
					else if($ItemTypeID != "Non Inventory Part"){//cek jika item type bukan Non Inventory Part                 
						throw new Exception("Item type salah, item type ini bukan Non Inventory Part");//pesan yang diambil dr helper : notices_import_file_helper.php
					}
					else if(empty($ItemCategoryID)){//cek jika item kategory kosong                            
						throw new Exception(noticesImport("denied", ["column"=>"Item Kategori","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
					}
					else if(empty($get_item_kategori->SvcCategoryName)){
						throw new Exception(noticesImport("notfound", ["column"=>"Item Kategori","code"=>$ItemCategoryID,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
					}
					else if(in_array($ItemCode, $tempArrayItemCode)){//ini utk pengecekkan klo di data itemcode yg akan dimasukkan ga blh sudah ada di table item
						throw new Exception(noticesImport("duplicate", ["column"=>"Item No.","code"=>$ItemCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
					}
					else if(!empty($get_item_code->ItemCode)){//ini utk pengecekkan klo di data itemcode yg akan dimasukkan ga blh sudah ada di table item
						throw new Exception(noticesImport("sameInTable", ["column"=>"Item No.","code"=>$ItemCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
					}
					else{
						$tempArrayItemCode[]= $ItemCode;//temporary data item code
						$sourceDate         = date('Y-m-d');
						/*=============Penomeran item code by initial ===============*/
						$dataitemcategori 	= $this->m_import_transaction->create_initial_code_by_name($ItemCategoryID_Trouper);
						$New_Item_code      = $get_item_kategori->InitialCategory.'-'.$dataitemcategori;
						/*=============END Penomeran item code by initial ===============*/
						$data_item = array(
							'SvcCategoryID' 	=> $get_item_kategori->SvcCategoryID,
							'SvcDetailName' 	=> $ItemDesc,
							'SvcDetailDesc' 	=> $ItemDesc,
							'SvcDetailUnit' 	=> $ItemUnit,
							'SvcPPh23Status' 	=> 0,
							'LastUser' 			=> $this->session->userdata('username')
						);
						$dataImport['data_item'][] = $data_item;

						$data_hisimport_detail = array(
							'ImportTransID'     => $num,
							'SourceNumber'      => $ItemDesc,
							'TransType'         => $TransType, 
							'SourceDate'        => $sourceDate,
							'ImportNumber'      => $number_data,
							'LastUser'          => $this->session->userdata('username')
						);	
						$dataImport['data_hisimport_detail'][] = $data_hisimport_detail;                            
					}
				}
				$rstImport = $this->m_import_transaction->importItemExpense($dataImport);
				if($rstImport){
					$result['status']   = true;
					$result['message']  = get_notification('insert', 1);
					//$result['message']  = noticesImport("success",[]);
				}else{
					$result['status']   = false;
					$result['message']  = get_notification('insert', 0);
					//$result['message']  = noticesImport("failed",[]);
				}
				echo json_encode($result);
				
			}
			
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
	}
	
	public function import_ap_transaction(){
		try{
			ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];

            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
                $objWriter      = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount     = $objPHPExcel->getSheetCount();

                //================ RULE BARU ==============================//
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				if(notCaseSensitifNotSpace($sheetData[6]['A'])!=notCaseSensitifNotSpace("Vendor No.")){
					throw new Exception("Maaf transaksi upload gagal Header Vendor No. tidak berada di kolom [A] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['B'])!=notCaseSensitifNotSpace("Vendor Name")){
					throw new Exception("Maaf transaksi upload gagal Header Vendor Name tidak berada di kolom [B] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['C'])!=notCaseSensitifNotSpace("Invoice No.")){
					throw new Exception("Maaf transaksi upload gagal Header Invoice No. Name tidak di kolom [C] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['D'])!=notCaseSensitifNotSpace("Invoice Date")){
					throw new Exception("Maaf transaksi upload gagal Header Invoice Date Name tidak di kolom [C] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['E'])!=notCaseSensitifNotSpace("Due Date")){
					throw new Exception("Maaf transaksi upload gagal Header Due Date Name tidak di kolom [E] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['F'])!=notCaseSensitifNotSpace("Terms")){
					throw new Exception("Maaf transaksi upload gagal Header Terms Name tidak di kolom [F] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['G'])!=notCaseSensitifNotSpace("Description")){
					throw new Exception("Maaf transaksi upload gagal Header Description Name tidak di kolom [G] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['H'])!=notCaseSensitifNotSpace("Invoice Amount")){
					throw new Exception("Maaf transaksi upload gagal Header Invoice Amount Name tidak di kolom [H] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['I'])!=notCaseSensitifNotSpace("Prime Owing")){
					throw new Exception("Maaf transaksi upload gagal Header Prime Owing Name tidak di kolom [I] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['J'])!=notCaseSensitifNotSpace("Tax Owing")){
					throw new Exception("Maaf transaksi upload gagal Header Tax Owing Name tidak di kolom [J] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['K'])!=notCaseSensitifNotSpace("Rate")){
					throw new Exception("Maaf transaksi upload gagal Header Rate Name tidak di kolom [K] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['M'])!=notCaseSensitifNotSpace("Currency")){
					throw new Exception("Maaf transaksi upload gagal Header Currency Name tidak di kolom [M] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[6]['Q'])!=notCaseSensitifNotSpace("Branch")){
					throw new Exception("Maaf transaksi upload gagal Header Branch Name tidak di kolom [Q] silahkan periksa kembali");
				}
				
				$this->db->trans_begin();
				$sourceDate     = date('Y-m-d');
				$TransType      = 'Ap_Transaction';
				$DataType       = 'Insert';
				$status         = 1;		
				$num            = $this->m_import_transaction->num_importtrans();
				$number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
				$data_hisimport = array(
					'ImportTransID' => $num,
					'TransType' 	=> $TransType, 
					'DataType'      => $DataType, 
					'ImportStatus' 	=> $status,
					'LastEdited' 	=> date('Y-m-d'),
					'LastUser'      => $this->session->userdata('username')
				);
				$insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
				
				for($i=7; $i<=$lastRow; $i++){
					if (count($this->arr_number['PI']) < 1) {
                        $Purchase_number = $this->m_purchase_invoice->create_pi_number();
                        array_push($this->arr_number['PI'], $Purchase_number);
                    } else {
                        $index_number = count($this->arr_number['PI']) - 1;
                        $pi_number_before = $this->arr_number['PI'][$index_number];
                        $arr_no = explode("/", $pi_number_before);
                        $no_explode = $arr_no[2];
                        $ordinal_number = sprintf("%03s", (int) $no_explode + 1);
                        $Purchase_number = $arr_no[0] . '/' . $arr_no[1] . '/' . $ordinal_number;

                        array_push($this->arr_number['PI'], $Purchase_number);
                    }
					
					$OldVendorCode      = upperNotSpace($sheetData[$i]['A']);
					$VendorName         = $sheetData[$i]['B'];
					$InvoiceNo          = $sheetData[$i]['C'];
					$InvoiceDate        = $sheetData[$i]['D'];
					
					$usage_date     	= explode(" ",$InvoiceDate);
                    $mont_usage     	= dateMMMtoMM($usage_date[1]);
                    $InvoiceDate_Exp    = $usage_date[2].'-'.$mont_usage.'-'.$usage_date[0];
					
					$DueDate        	= $sheetData[$i]['E'];
					$usage_date_due     = explode(" ",$DueDate);
                    $mont_usage_due     = dateMMMtoMM($usage_date_due[1]);
                    $DueDate_Exp      	= $mont_usage_due[2].'-'.$mont_usage_due.'-'.$mont_usage_due[0];
					
					$Terms        		= $sheetData[$i]['F'];
					$Desc        		= $sheetData[$i]['G'];
					$InvoiceAmount      = $sheetData[$i]['H'];
					$OutStanding      	= $sheetData[$i]['I'];
					$TaxOwing      		= $sheetData[$i]['J'];
					$Rate      			= $sheetData[$i]['K'];
					$Currency      		= $sheetData[$i]['M'];
					$Branch      		= $sheetData[$i]['Q'];
					
					$get_vendor_code 	= $this->m_import_transaction->get_vendor_code($Branch, $OldVendorCode);
					$Item_code 			= "ITM-MGRS";
					$get_inventori 		= $this->m_vendors->get_inventories($Item_code);
					/*if($OutStanding==null || $OutStanding==""){//cek jika item kosong                          
                          throw new Exception(noticesImport("denied", ["column"=>"Prime Owing","line"=>$i]));
                    }*/
						
					if($get_inventori== false){
						throw new Exception("Maaf item dengan kode " . $Item_code . " Belum Tersedia Di Inventori");
					}
					$item_inventori 	= $get_inventori->ItemCode;
                    $item_kategori 		= $get_inventori->ItemCategoryID;
					
					$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
                    $PayableAccount = $this->m_account_journal->get_cat_purchase_account('Payable', $item_kategori, $Currency); // Hutang Dagang
					if ($OpeningBalance == false) {
                        throw new Exception("Maaf Transaksi gagal dibuat Coa Opening Balance Belum Tersedia, di master COA");
                    }
                    else if ($PayableAccount == false) {
                        throw new Exception("Maaf Transaksi gagal dibuat Preference Belum Lengkap Untuk Kategori ITEM MIGRASI");
                    }
					else{
						if(($OutStanding > 0)){                          
							$data_purchase_invoice = array(
								'BranchCode' => $Branch,
								'VendorCode' => strtoupper($get_vendor_code->VendorCode),
								'PInvNumber' => $Purchase_number,
								'PRecNumber' => $Purchase_number,
								'VendorAddress' => $get_vendor_code->VendorAddress,
								'PInvDate' => date('Y-m-d'),
								'PRecDate' => date('Y-m-d'),
								'PInvDueDate' => $DueDate_Exp,
								//'FiscalRate' 		=> $tgl_tempo,
								'CurrencyRate' => $Rate,
								'CurrencyCode' => $Currency,
								'ImportStatus' => 1,
								'TransStatus' => 1,
								'FOBID' => 1,
								'TermsPaymentID' => $get_vendor_code->TermsPaymentID,
								'ShipmentDate' => date("Y-m-d", strtotime($PInvDate)),
								'ShipmentID' => 1,
								
								'PInvSubTotal' => $OutStanding,
								'PInvTotalAmount' => $OutStanding,
								'PInvTotalInvoice' => $OutStanding,
						
								'AppLevel1Status' => 1,
								'PInvDesc' => "Item Migrasi Database, Tgl Invoice ".$PInvDate."",
								'OldPInvNumber' => $InvoiceNo,
								'AppLevel1Code' => $this->session->userdata("username"),
								'AppLevel1Date' => date('Y-m-d'),
								'AppLevel2Status' => 1,
								'AppLevel2Code' => $this->session->userdata("username"),
								'AppLevel2Date' => date('Y-m-d'),
								'CreatedBy' => $this->session->userdata("username"),
								'CreatedAt' => date('Y-m-d'),
								'LastUser' => $this->session->userdata("username")
							);
							$result_insert = $this->m_purchase_invoice->insert($data_purchase_invoice);
							
							$data_detail_pi = array(
								'PRecNumber' => $Purchase_number,
								'PInvNumber' => $Purchase_number,
								'ItemCode' => $item_inventori,
								'ItemDesc' => 'Item Migrasi Database',
								'ItemQty' => 1,
								'ItemCategoryID' => $item_kategori,
								'ItemCategoryCode' => $item_kategori,
								'ItemUnit' => 'Unit',
								'ItemPrice' => $OutStanding,
								'ItemAmount' => $OutStanding,
								'ItemTotalAmount' => $OutStanding,
								'LastUser' => $this->session->userdata("username")
							);
							$result_insert = $this->m_purchase_invoice->insert_detail($data_detail_pi);
							
							$data_payment = array(
								'BranchCode' => $Branch,
								'VendorCode' => strtoupper($get_vendor_code->VendorCode),
								'InvoiceNumber' => $Purchase_number,
								'InvoiceDate' => date('Y-m-d'),
								'InvoiceCurrCode' => $Currency,
								'InvoiceCurrRate' => $Rate,
								'InvoiceFiscalRate' => 1,
								'InvoiceTotalDP' => 0,
								'ItemCategoryID' => $item_kategori,
								'ItemCategoryCode' => $item_kategori,
								'ItemStatus' => 0,
								'InvoiceType' => 0,
								'InvoicePurchase' => $OutStanding,
								'InvoiceAmount' => $OutStanding,
								'InvoiceOwing' => $OutStanding,
								'ItemCategoryRatio' => 100,
								'PPnFiscalStatus' => 0,
								'LastUser' => $this->session->userdata("username")
							);
							$result_insert = $this->m_purchase_invoice->insert_payment($data_payment);
							
		
							$opening_journal = $Currency == 'IDR' ? $OutStanding : $OutStanding * $Rate;
							$opening_currency = $OutStanding;
		
							$journal_unbilled = array(
								'PInvDate' => date('Y-m-d'),
								'PInvNumber' => $Purchase_number,
								'PInvDesc' => "Migrasi",
								'PInvAccountNumber' => $OpeningBalance->AccountNumber,
								'PInvSaldoDebet' => $opening_journal,
								'PInvSaldoCredit' => 0,
								'AmountCurrency' => $opening_currency,
								'PInvSignStatus' => 1,
								'ItemCategoryCode' => $item_kategori,
								'LastUser' => $this->session->userdata("username")
							);
							$result_insert = $this->m_purchase_invoice->insert_journal($journal_unbilled);
							
							$payable_value = $Currency == 'IDR' ? $OutStanding : $OutStanding * $Rate;
							$payable_currency = $OutStanding;
		
							$journal_purchase = array(
								'PInvDate' => date('Y-m-d'),
								'PInvNumber' => $Purchase_number,
								'PInvDesc' => "Migrasi",
								'PInvAccountNumber' => $PayableAccount->AccountNumber,
								'PInvSaldoDebet' => 0,
								'PInvSaldoCredit' => $payable_value,
								'AmountCurrency' => $payable_currency,
								'PInvSignStatus' => 0,
								'ItemCategoryCode' => $item_kategori,
								'LastUser' => $this->session->userdata("username")
							);
							$result_insert = $this->m_purchase_invoice->insert_journal($journal_purchase);
							
							$data_hisimport_detail = array(
								'ImportTransID'     => $num,
								'SourceNumber'      => $Purchase_number,
								'TransType'         => $TransType, 
								'SourceDate'        => $sourceDate,
								'BranchCode'        => $Branch,
								'ImportNumber'      => $number_data,
								'LastUser'          => $this->session->userdata('username')
							);	
							$result_insert = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
							//$this->trans_data['data_hisimport_detail']['data'][]         = $data_hisimport_detail;
							
							$data_update_invoice_group = array(
								'AppFinished' => 1
							);
							$result_insert = $this->m_purchase_invoice->update($data_update_invoice_group, $Purchase_number);
						}
					}
				}
				
				/* =============================trans roll back dan trans commit============================/ */
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$result['status']   = true;
					$result['message']  = get_notification('insert', 0);
				} else {
					$this->db->trans_commit();
					$result['status']   = false;
					$result['message']  = get_notification('insert', 1);
				}
				/* ==================================end====================================================== */
				echo json_encode($result);
			}
		}
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
			$this->db->trans_rollback();
            echo json_encode($result);
        }
	}
	
	public function import_ar_transaction(){
		try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];

            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
                $objWriter      = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount     = $objPHPExcel->getSheetCount();

                //================ RULE BARU ==============================//
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				if(notCaseSensitifNotSpace($sheetData[5]['A'])!=notCaseSensitifNotSpace("Customer No.")){
					throw new Exception("Maaf transaksi upload gagal Header Customer No. tidak berada di kolom [A] silahkan periksa kembali");//pesan yang diambil dr helper : notices_import_file_helper.php
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['B'])!=notCaseSensitifNotSpace("Customer Name")){
					throw new Exception("Maaf transaksi upload gagal Header Customer Name tidak berada di kolom [B] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['C'])!=notCaseSensitifNotSpace("Invoice No.")){
					throw new Exception("Maaf transaksi upload gagal Header Invoice No. Name tidak di kolom [C] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['D'])!=notCaseSensitifNotSpace("Invoice Date")){
					throw new Exception("Maaf transaksi upload gagal Header Invoice Date Name tidak di kolom [D] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['E'])!=notCaseSensitifNotSpace("Due Date")){
					throw new Exception("Maaf transaksi upload gagal Header Due Date Name tidak di kolom [E] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['F'])!=notCaseSensitifNotSpace("Terms Net Days")){
					throw new Exception("Maaf transaksi upload gagal Header Terms Net Days Name tidak di kolom [F] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['G'])!=notCaseSensitifNotSpace("Description")){
					throw new Exception("Maaf transaksi upload gagal Header Description tidak di kolom [G] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['H'])!=notCaseSensitifNotSpace("Invoice Amount")){
					throw new Exception("Maaf transaksi upload gagal Header Invoice Amount tidak di kolom [H] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['I'])!=notCaseSensitifNotSpace("Prime Owing")){
					throw new Exception("Maaf transaksi upload gagal Header Prime Owing tidak di kolom [I] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['J'])!=notCaseSensitifNotSpace("Tax Owing")){
					throw new Exception("Maaf transaksi upload gagal Header Tax Owing tidak di kolom [J] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['K'])!=notCaseSensitifNotSpace("Rate")){
					throw new Exception("Maaf transaksi upload gagal Header Rate tidak di kolom [K] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['L'])!=notCaseSensitifNotSpace("Age fr Due")){
					throw new Exception("Maaf transaksi upload gagal Header Age fr Due tidak di kolom [L] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['M'])!=notCaseSensitifNotSpace("Customer Currency Name")){
					throw new Exception("Maaf transaksi upload gagal Header Customer Currency Name tidak di kolom [M] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['N'])!=notCaseSensitifNotSpace("AR Account Name")){
					throw new Exception("Maaf transaksi upload gagal Header AR Account Name tidak di kolom [N] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['O'])!=notCaseSensitifNotSpace("Customer Group")){
					throw new Exception("Maaf transaksi upload gagal Header Customer Group tidak di kolom [O] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['P'])!=notCaseSensitifNotSpace("Customer Sub Group")){
					throw new Exception("Maaf transaksi upload gagal Header Customer Sub Group tidak di kolom [P] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['Q'])!=notCaseSensitifNotSpace("Customer Wilayah")){
					throw new Exception("Maaf transaksi upload gagal Header Customer Wilayah tidak di kolom [Q] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['R'])!=notCaseSensitifNotSpace("Last Cheque Date")){
					throw new Exception("Maaf transaksi upload gagal Header Last Cheque Date tidak di kolom [R] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['S'])!=notCaseSensitifNotSpace("Inv. Tax No.")){
					throw new Exception("Maaf transaksi upload gagal Header Inv. Tax No. tidak di kolom [S] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['T'])!=notCaseSensitifNotSpace("Ship Via Name")){
					throw new Exception("Maaf transaksi upload gagal Header Ship Via Name tidak di kolom [T] silahkan periksa kembali");
				}
				else if(notCaseSensitifNotSpace($sheetData[5]['U'])!=notCaseSensitifNotSpace("Branch")){
					throw new Exception("Maaf transaksi upload gagal Header Branch tidak di kolom [U] silahkan periksa kembali");
				}
				
				$dataImport = [];
				
				$tempArrayItemCode                  = [];
				$this->db->trans_begin();
				$sourceDate     = date('Y-m-d');
				$TransType      = 'Ar_Transaction';
				$DataType       = 'Insert';
				$status         = 1;		
				$num            = $this->m_import_transaction->num_importtrans();
				$number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
				$data_hisimport = array(
					'ImportTransID' => $num,
					'TransType' 	=> $TransType, 
					'DataType'      => $DataType, 
					'ImportStatus' 	=> $status,
					'LastEdited' 	=> date('Y-m-d'),
					'LastUser'      => $this->session->userdata('username')
				);
				$insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
				
				//$this->trans_data['data_hisimport']['data']         = $data_hisimport;
				
				$invoice_no = " ";
				
				for($i=6; $i<=$lastRow; $i++){
					if (count($this->arr_number['SI']) < 1) {
                        $sales_in = $this->m_sales_invoice->create_si_number(date('d-m-Y'));
                        array_push($this->arr_number['SI'], $sales_in);
                    } else {
                        $index_number = count($this->arr_number['SI']) - 1;
                        $si_number_before = $this->arr_number['SI'][$index_number];
                        $arr_no = explode("/", $si_number_before);
                        $no_explode = $arr_no[2];
                        $ordinal_number = sprintf("%03s", (int) $no_explode + 1);
                        $sales_in = $arr_no[0] . '/' . $arr_no[1] . '/' . $ordinal_number;

                        array_push($this->arr_number['SI'], $sales_in);
                    }
					
					$OldCustomerCode        = upperNotSpace($sheetData[$i]['A']);
					$CustomerName           = $sheetData[$i]['B'];
					$OldInvoice           	= $sheetData[$i]['C'];
					$InvoiceDate           	= $sheetData[$i]['D'];
					
					$usage_date     		= explode(" ",$InvoiceDate);
                    $mont_usage     		= dateMMMtoMM($usage_date[1]);
                    $InvoiceDate_Exp      	= $usage_date[2].'-'.$mont_usage.'-'.$usage_date[0];
							
					$DueDate           		= $sheetData[$i]['E'];
					
					$usage_date_due     	= explode(" ",$DueDate);
                    $mont_usage_due     	= dateMMMtoMM($usage_date_due[1]);
                    $DueDate_Exp      		= $mont_usage_due[2].'-'.$mont_usage_due.'-'.$mont_usage_due[0];
					
					$Terms           		= $sheetData[$i]['F'];
					$Desc           		= $sheetData[$i]['G'];
					$InvAmount           	= $sheetData[$i]['H'];
					$OutStanding           	= $sheetData[$i]['I'];
					$TaxOwing           	= $sheetData[$i]['J'];
					$Rate           		= $sheetData[$i]['K'];
					$CurrencyCode           = $sheetData[$i]['M'];
					$ShipVia           		= $sheetData[$i]['T'];
					
					$Branch           		= $sheetData[$i]['U'];
					$get_customer_code 		= $this->m_import_transaction->get_customer_code($Branch, $OldCustomerCode);
					
					/*if($OutStanding==null || $OutStanding==""){//cek jika item kosong                          
                          throw new Exception(noticesImport("denied", ["column"=>"Prime Owing","line"=>$i]));
                    }*/
					
					if(empty($get_customer_code->CustomerCode)){
						throw new Exception(noticesImport("notfound", ["column"=>"Customer No.","code"=>$OldCustomerCode,"di"=>"Master Data","line"=>$i]));
					}
					
					/*
					  Cek inventori item exis not exis
                    */
					$Item_code = "ITM-MGRS";
                    $ItemDesc = "ITEM MIGRASI UNTUK SEMUA CURRENCY";
					
                    $get_inventori = $this->m_customer->get_inventories($Item_code);
					if($get_inventori== false){
						throw new Exception("Maaf item dengan kode " . $Item_code . " Belum Tersedia Di Inventori");
					}
					
					$item_inventori = $get_inventori->ItemCode;
                    $item_kategori = $get_inventori->ItemCategoryID;
                    /* ======================End============================================================================ */
					
					$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
					$ReceivableAccount = $this->m_account_journal->get_cat_sales_account('SRAccountReceivable', $item_kategori, $CurrencyCode);
					
                    if ($OpeningBalance == false) {
                        throw new Exception("Maaf Transaksi gagal dibuat Coa Opening Balance Belum Tersedia, di master COA");
                    }
					else if ($ReceivableAccount == false) {
                        throw new Exception("Maaf Transaksi gagal dibuat Preference Belum Lengkap Untuk Kategori ".$item_kategori."");
                    }
					else{
						if(($OutStanding > 0)){
							$data_sales_invoice = array(
								'BranchCode' => $Branch,
								'CustomerCode' => strtoupper($get_customer_code->CustomerCode),
								'SInvNumber' => $sales_in,
								'DOrdNumber' => $sales_in,
								'SOrdNumber' => $sales_in,
								'ShippingAddress' => $get_customer_code->CustomerAddress,
								'BillingAddress' => $get_customer_code->CustomerAddress,
								'TermsPaymentID' => $get_customer_code->TermsPaymentID,
								'ImportStatus' => 1,
								'SInvDate' => date('Y-m-d'),
								'ShipDate' => date("Y-m-d", strtotime($InvoiceDate_Exp)),
								'ShipmentID' => 1,
								'FOBID' => 1,
								'CustPONumber' => $sales_in,
								'CurrencyCode' => $CurrencyCode,
								'CurrencyRate' => $Rate,
								'DOrdDate' => date('Y-m-d'),
								'SInvDueDate' => $DueDate_Exp,
								'TransStatus' => 1,
								'AppLevel1Status' => 1,
								'SInvEstFreight' => 0,
								
								'SInvSubTotal' => $OutStanding,
								'SInvTotalAmount' => $OutStanding,
							
								'SInvDesc' => "Item Migrasi Database, Tgl Invoice (".$InvoiceDate.")",
								'OldSInvNumber' => $OldCustomerCode,
								'FiscalRate' => 1,
								
								'AppLevel1Code' => $this->session->userdata("username"),
								'AppLevel1Date' => date('Y-m-d'),
								'CreatedBy' => $this->session->userdata("username"),
								'CreatedAt' => date('Y-m-d'),
								'LastUser' => $this->session->userdata("username")
							);
							$result_insert = $this->m_sales_invoice->insert($data_sales_invoice);
							//$this->trans_data['data_sales_invoice']['data'][]         = $data_sales_invoice;
							
							$data_detail_si = array(
								'SOrdNumber' => $sales_in,
								'SInvNumber' => $sales_in,
								'ItemCode' => $item_inventori,
								'ItemQty' => 1,
								'ItemDesc' => $ItemDesc,
								'ItemUnit' => 'Unit',
								'ItemCategoryID' => $item_kategori,
								'ItemPrice' => $OutStanding,
								'ItemPriceCogs' => 0,
								'SalesmanCode' => NULL,
								'ItemAmount' => $OutStanding,
								'ItemTotalAmount' => $OutStanding,
								'ItemCategoryID' => $item_kategori,
								'ItemCategoryCode' => $item_kategori,
								'ItemType' => 0,
								'LastUser' => $this->session->userdata("username")
							);
							$result_insert = $this->m_sales_invoice->insert_detail($data_detail_si);
							//$this->trans_data['data_detail_si']['data'][]         = $data_detail_si;
							
							$data_invoice_receipt = array(
								'BranchCode' => $this->session->userdata('branch'),
								'CustomerCode' => strtoupper($get_customer_code->CustomerCode),
								'InvoiceCurrCode' => $CurrencyCode,
								'InvoiceCurrRate' => doubleval($Rate),
								'InvoiceFiscalRate' => 1,
								'InvoiceNumber' => $sales_in,
								'InvoiceDate' => date('Y-m-d'),
								'ItemCategoryID' => $item_kategori,
								'ItemCategoryCode' => $item_kategori,
								'InvoiceType' => 0,
								'InvoiceAmount' => doubleval($OutStanding),
								'InvoiceOwing' => doubleval($OutStanding),
								'InvoiceCurrency' => doubleval($OutStanding),
								'ItemCategoryRatio' => 100,
							
								'PPnFiscalStatus' => 0,
								'LastUser' => $this->session->userdata('username')
							);
							$result_insert = $this->m_sales_invoice->insert_sinv_receipt($data_invoice_receipt);
							//$this->trans_data['data_invoice_receipt']['data'][]         = $data_invoice_receipt;
							
							//ganti ke opening balance untuk pasangan disini
							$Openig_journal = $CurrencyCode == 'IDR' ? $OutStanding : $OutStanding * $Rate;
							$Openig_currency = $OutStanding;
		
							$data_Inventori_journal = array(
								'SInvDate' => date('Y-m-d'),
								'SInvNumber' => $sales_in,
								'SInvAccountNumber' => $OpeningBalance->AccountNumber,
								'SInvSaldoDebet' => 0,
								'SInvSaldoCredit' => $Openig_journal,
								'AmountCurrency' => doubleval($Openig_currency),
								'SInvSignStatus' => 0,
								'LastUser' => $this->session->userdata('username')
							);
							
							$result_insert = $this->m_sales_invoice->insert_journal($data_Inventori_journal);
							
							//$this->trans_data['data_Inventori_journal']['data'][]         = $data_Inventori_journal;
							
							$receivable_journal = $CurrencyCode == 'IDR' ? $OutStanding : $OutStanding * $Rate;
							$receivable_currency = $OutStanding;
		
							$data_receivable_journal = array(
								'SInvDate' => date('Y-m-d'),
								'SInvNumber' => $sales_in,
								'SInvAccountNumber' => $ReceivableAccount->AccountNumber,
								'SInvSaldoDebet' => $receivable_journal,
								'SInvSaldoCredit' => 0,
								'AmountCurrency' => doubleval($receivable_currency),
								'SInvSignStatus' => 0,
								'LastUser' => $this->session->userdata('username')
							);
							$result_insert = $this->m_sales_invoice->insert_journal($data_receivable_journal);
							//$this->trans_data['data_receivable_journal']['data'][]         = $data_receivable_journal;
							
							$data_hisimport_detail = array(
								'ImportTransID'     => $num,
								'SourceNumber'      => $sales_in,
								'TransType'         => $TransType, 
								'SourceDate'        => $sourceDate,
								'BranchCode'        => $Branch,
								'ImportNumber'      => $number_data,
								'LastUser'          => $this->session->userdata('username')
							);	
							$result_insert = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
							//$this->trans_data['data_hisimport_detail']['data'][]         = $data_hisimport_detail;
							
							$data_update_invoice_group = array(
								'AppFinished' => 1
							);
							$result_insert = $this->m_sales_invoice->update($data_update_invoice_group,$sales_in);
							//$this->trans_data['data_update_invoice_group']['data'][]         = $data_update_invoice_group;
							//$this->trans_data['data_update_invoice_group']['InvoiceNumber'] = $sales_in;
						}
					} 
				}
				
				//$result_return = $this->m_import_transaction->import_ar_transaction($this->trans_data);

            	//$this->trans_data = [];
				/* =============================trans roll back dan trans commit============================/ */
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					$result['status']   = true;
					$result['message']  = get_notification('insert', 0);
				} else {
					$this->db->trans_commit();
					$result['status']   = false;
					$result['message']  = get_notification('insert', 1);
				}
				/* ==================================end====================================================== */
				echo json_encode($result);
				
			}
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
	}
	
    public function import_cust(){
        try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];            
            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..                
                $objPHPExcel = PHPExcel_IOFactory::load($filename);
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount = $objPHPExcel->getSheetCount();
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();

                if( notCaseSensitifNotSpace($sheetData[1]['A'])==notCaseSensitifNotSpace("Customer No.") && //pengecekkan header huruf tidak case sensitif dan spasi tidak dipermasalahkan, jd saat pengecekkan menghilangkan spasi serta huruf dipaksa sama jenisnya(Upper/lower),yg dipakai sekarang upper. ini function diambil dari helper customstring_helper.php
                    notCaseSensitifNotSpace($sheetData[1]['B'])==notCaseSensitifNotSpace("Customer Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['D'])==notCaseSensitifNotSpace("Currency Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['E'])==notCaseSensitifNotSpace("Phone") &&
                    notCaseSensitifNotSpace($sheetData[1]['F'])==notCaseSensitifNotSpace("Contact Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['G'])==notCaseSensitifNotSpace("Address 1") &&
                    notCaseSensitifNotSpace($sheetData[1]['H'])==notCaseSensitifNotSpace("Address 2") &&
                    notCaseSensitifNotSpace($sheetData[1]['T'])==notCaseSensitifNotSpace("Term Net Days") &&
                    notCaseSensitifNotSpace($sheetData[1]['X'])==notCaseSensitifNotSpace("Wilayah")  &&
                    notCaseSensitifNotSpace($sheetData[1]['AB'])==notCaseSensitifNotSpace("Branch")    
                ){                           
                    $dataImport = [];
                    $dataImport['data_hisimport']       = [];
                    $dataImport['data_hisimport_detail']= [];
                    $dataImport['data_cust']            = [];
                    $tempArrayCode                      = [];
                    $lastRowNoCode                      = 0;

                    $sourceDate     = date('Y-m-d');
                    $TransType      = 'Customer';
                    $DataType       = 'Insert';
                    $status         = 1;		
                    $num            = $this->m_import_transaction->num_importtrans();
                    $number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
                    $data_hisimport = array(
                        'ImportTransID' => $num,
                        'TransType' 	=> $TransType, 
                        'DataType'      => $DataType, 
                        'ImportStatus' 	=> $status,
                        'LastEdited' 	=> date('Y-m-d'),
                        'LastUser'      => $this->session->userdata('username')
                    );
                    $dataImport['data_hisimport'][] = $data_hisimport;

                    for($i=2; $i<=$lastRow; $i++){
                        $OldCustomerCode    = upperNotSpace($sheetData[$i]['A']);
                        $CustomerName       = $sheetData[$i]['B'];
                        $CurrencyCode       = $sheetData[$i]['D'];
                        $Phone              = $sheetData[$i]['E'];
                        $ContactName        = $sheetData[$i]['F'];
                        $Addres             = $sheetData[$i]['G'].' '.$sheetData[$i]['H'];
                        $Term               = $sheetData[$i]['T'];
                        $Wilayah            = $sheetData[$i]['X'];
                        $BranchCode         = $sheetData[$i]['AB'];
                        $City_Trouper       = strtoupper($Wilayah); 

                        $City               = $sheetData[$i]['I'];
                        $Province           = $sheetData[$i]['J'];
                        $ZipCode            = $sheetData[$i]['K'];
                        $Country            = $sheetData[$i]['L'];
                        $Fax                = $sheetData[$i]['M'];
                        $Email              = $sheetData[$i]['N'];
                        $WebPage            = $sheetData[$i]['O'];
                        $Tax1               = $sheetData[$i]['P'];
                        $Tax2               = $sheetData[$i]['Q'];
                        $TaxNumber          = $sheetData[$i]['R'];
                        $Pkp                = $sheetData[$i]['S'];
                        $Memo               = $sheetData[$i]['U'];
                        $TaxType            = $sheetData[$i]['Y'];
                        $TaxAddres          = $sheetData[$i]['Z'].' '.$sheetData[$i]['AA'];

                        $get_currency       = $this->m_import_transaction->get_currency_code($CurrencyCode);
                        $get_customer       = $this->m_import_transaction->get_customer_code($BranchCode, $OldCustomerCode);
                        $check_num_oldcustomer=$this->m_import_transaction->check_num_oldcustomer_code($BranchCode, $OldCustomerCode);
                        $check_num_customer = $this->m_import_transaction->check_num_customer_code($BranchCode, $OldCustomerCode);
                        $get_term           = $this->m_import_transaction->get_term_code($Term);
                        $get_city           = $this->m_import_transaction->get_am_city($City_Trouper);
                        $City_DataBase_Trouper = strtoupper($get_city->CityName);

                        ///ceking database	
                        $state              = $get_city->StateCode;
                        $get_state          = $this->m_import_transaction->get_am_state($state);
                        $country_code       = $get_state->CountryCode;

                        if( ($OldCustomerCode==null || $OldCustomerCode=="") &&
                            (notCaseSensitifNotSpace($CustomerName)==null || notCaseSensitifNotSpace($CustomerName)=="") &&
                            (notCaseSensitifNotSpace($CurrencyCode)==null || notCaseSensitifNotSpace($CurrencyCode)=="") &&
                            (notCaseSensitifNotSpace($Phone)==null || notCaseSensitifNotSpace($Phone)=="") &&
                            (notCaseSensitifNotSpace($ContactName)==null || notCaseSensitifNotSpace($ContactName)=="") &&
                            (notCaseSensitifNotSpace($Addres)==null || notCaseSensitifNotSpace($Addres)=="") &&
                            (notCaseSensitifNotSpace($Term)==null || notCaseSensitifNotSpace($Term)=="") &&
                            (notCaseSensitifNotSpace($Wilayah)==null || notCaseSensitifNotSpace($Wilayah)=="") &&
                            (notCaseSensitifNotSpace($BranchCode)==null || notCaseSensitifNotSpace($BranchCode)=="")
                        ){//cek jika itemCode & $ItemDesc & $ItemTypeID & $ItemCategoryID kosong                        
                            //SKIP
                        }else if(($OldCustomerCode==null || $OldCustomerCode=="")){
                            throw new Exception(noticesImport("denied",["column"=>"Customer No","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(notCaseSensitifNotSpace($CustomerName)==null || notCaseSensitifNotSpace($CustomerName)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Customer Name","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(notCaseSensitifNotSpace($CurrencyCode)==null || notCaseSensitifNotSpace($CurrencyCode)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Currency Code","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(notCaseSensitifNotSpace($Term)==null || notCaseSensitifNotSpace($Term)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Term Net Days","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        /*else if(notCaseSensitifNotSpace($Wilayah)==null || notCaseSensitifNotSpace($Wilayah)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Wilayah","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }*/
                        else if(notCaseSensitifNotSpace($BranchCode)==null || notCaseSensitifNotSpace($BranchCode)==""){
                            throw new Exception(noticesImport("denied",["column"=>"BranchCode","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }                        
                        else if(in_array($OldCustomerCode, $tempArrayCode)){//ini utk pengecekkan klo di data itemcode yg akan dimasukkan ga blh sudah ada di table item
                            throw new Exception(noticesImport("duplicate", ["column"=>"Customer Code","code"=>$OldCustomerCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if($BranchCode != $sess_branch		= $this->session->userdata('branch')){
                            throw new Exception(noticesImport("notMatchLogin", ["column"=>"Branch","code"=>$BranchCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(empty($get_currency->CurrencyCode)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Currency","code"=>$ItemCategoryID,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if($check_num_oldcustomer){
                            throw new Exception(noticesImport("sameInTable", ["column"=>"Old Customer No","code"=>$OldCustomerCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if($check_num_customer){
                            throw new Exception(noticesImport("sameInTable", ["column"=>"Customer No","code"=>$OldCustomerCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        /*else if(empty($get_city->CityName)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Wilayah/Kota","code"=>$get_city->CityName,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }*/
                        else if(empty($get_term)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Term","code"=>$get_term,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else{
                            $tempArrayCode[]    = $OldCustomerCode;                            
                            $sess_brach		= $this->session->userdata('branch');
                            $ceknourut          = $this->m_customer->get_last_customer_code($sess_brach);
                            if($lastRowNoCode>0){
                                $lastRowNoCode  = $lastRowNoCode+1;
                                $pay_numb3	= $lastRowNoCode;                                
                                $count_recnumb = strlen($pay_numb3);
                                if($count_recnumb == 1){
                                        $next_customer_numb = '0000'.$pay_numb3;
                                }elseif($count_recnumb == 2){
                                        $next_customer_numb = '000'.$pay_numb3;
                                }elseif($count_recnumb == 3){
                                        $next_customer_numb = '00'.$pay_numb3;
                                }elseif($count_recnumb == 4){
                                        $next_customer_numb = '0'.$pay_numb3;
                                }elseif($count_recnumb == 5){
                                        $next_customer_numb = $pay_numb3;
                                }

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

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

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

                                    $branch = $sess_brach;
                                }else{
                                    $lastRowNoCode = 1;
                                    $branch = $sess_brach;
                                    $next_customer_numb 	= '0001';
                                }
                            }
                            $CustomerCode               = $branch.'-'.$next_customer_numb;    

                            if(notCaseSensitifNotSpace($Phone)==null || notCaseSensitifNotSpace($Phone)==""){
                                $Phone 	= 0;
                            }
                            if(notCaseSensitifNotSpace($ContactName)==null || notCaseSensitifNotSpace($ContactName)==""){
                                $ContactName = "NA";
                            }
                            if(notCaseSensitifNotSpace($Addres)==null || notCaseSensitifNotSpace($Addres)==""){
                                $Addres  = "NA";
                            }                            					
                            $dataCust = array(
                                'BranchCode'            => $BranchCode,
                                'CustomerCode'          => $CustomerCode,
                                'OldCustomerCode'       => $OldCustomerCode,
                                'CustomerName'          => $CustomerName.' '.$get_currency->CurrencyCode,
                                'CustomerAddress'       => $Addres,
                                'CustTaxAddress'        => $TaxAddres,
                                'CustomerCity'          => $get_city->CityCode,
                                'CustomerState'         => $get_state->StateCode,
                                'CustomerCountry'       => $country_code,
                                'CustomerPostalCode'    => $ZipCode,
                                'PhoneNumber'           => $Phone,
                                'FacsimileNumber'       => $Fax,
                                'ContactPerson'         => $ContactName,
                                'EmailAddress'          => $Email,
                                'WebAddress'            => $WebPage,
                                'TermsPaymentID'        => $get_term,
                                'CurrencyCode'          => $get_currency->CurrencyCode,
                                'CurrencyMemo'          => $Memo,
                                'Taxes1Code'            => $Tax1,
                                'Taxes2Code'            => $Tax2,
                                'TaxesNumber'           => $TaxNumber,
                                'PPKPNumber'            => $Pkp,
                                //'TaxesTypeID'         => ,
                                'TransStatus'           => 1,
                                'LastUser'              => $this->session->userdata('username')
                            );					
                            $dataImport['data_cust'][]  = $dataCust;

                            $data_hisimport_detail = array(
                                'BranchCode' 		=> $BranchCode,
                                'ImportTransID' 	=> $num,
                                'SourceNumber' 		=> $OldCustomerCode,
                                'TransType' 		=> $TransType, 
                                'SourceDate' 		=> $sourceDate,
                                'ImportNumber' 		=> $number_data,
                                'LastUser'              => $this->session->userdata('username')
                            );
                            $dataImport['data_hisimport_detail'][] = $data_hisimport_detail;
                        }
                    }//end for

                    $rstImport = $this->m_import_transaction->importCustomerMaster($dataImport);
                    //$rstImport = true;
                    if($rstImport){
                        $result['status']   = true;
                        $result['message']  = get_notification('insert', 1);
                        //$result['message']  = noticesImport("success",[]);
                    }else{
                        $result['status']   = false;
                        $result['message']  = get_notification('insert', 0);
                        //$result['message']  = noticesImport("failed",[]);
                    }  
                    echo json_encode($result);
                }
                else if( notCaseSensitifNotSpace($sheetData[1]['A'])!=notCaseSensitifNotSpace("Customer No.")){
                    throw new Exception(noticesImport("notCell",["column"=>"Customer No","code"=>"A1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['B'])!=notCaseSensitifNotSpace("Customer Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Customer Name","code"=>"B1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['D'])!=notCaseSensitifNotSpace("Currency Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Currency Name","code"=>"D1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['E'])!=notCaseSensitifNotSpace("Phone")){
                    throw new Exception(noticesImport("notCell",["column"=>"Phone","code"=>"E1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['F'])!=notCaseSensitifNotSpace("Contact Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Contact Name","code"=>"F1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['G'])!=notCaseSensitifNotSpace("Address 1")){
                    throw new Exception(noticesImport("notCell",["column"=>"Address 1","code"=>"G1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['H'])!=notCaseSensitifNotSpace("Address 2")){
                    throw new Exception(noticesImport("notCell",["column"=>"Address 2","code"=>"H1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['T'])!=notCaseSensitifNotSpace("Term Net Days")){
                    throw new Exception(noticesImport("notCell",["column"=>"Term Net Days","code"=>"T1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['X'])!=notCaseSensitifNotSpace("Wilayah")){
                    throw new Exception(noticesImport("notCell",["column"=>"Wilayah","code"=>"X1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['AB'])!=notCaseSensitifNotSpace("BranchCode")){
                    throw new Exception(noticesImport("notCell",["column"=>"BranchCode","code"=>"AB1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }
                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);
        }
    }

    public function import_custLAMA(){
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];
            $objPHPExcel = PHPExcel_IOFactory::load($filename);
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
            $sheetCount = $objPHPExcel->getSheetCount();
            for($i=0; $i<=$sheetCount; $i++) {		
                    if($i == 0){
                            $objPHPExcel->setActiveSheetIndex($i);
                            $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                            $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();

                            $OldCustomerCode_1 = '';
                            for($h=2; $h<=$lastRow; $h++){
                                    $OldCustomerCode 	= $sheetData[$h]['A'];
                                    $CurrencyCode 	= $sheetData[$h]['D'];
                                    $BranchCode 	= $sheetData[$h]['AB'];
                                    $Wilayah 		= $sheetData[$h]['X'];
                                    $Term 			= $sheetData[$h]['T'];
                                    $CustomerName 	= $sheetData[$h]['B'];
                                    $Phone 			= $sheetData[$h]['E'];
                                    $Addres 		= $sheetData[$h]['G'].' '.$sheetData[$h]['H'];
                                    $ContactName 	= $sheetData[$h]['F'];

                                    $City_Trouper = strtoupper($Wilayah);

                                    $get_currency 	= $this->m_import_transaction->get_currency_code($CurrencyCode);
                                    $get_customer 	= $this->m_import_transaction->get_customer_code($BranchCode, $OldCustomerCode);
                                    $get_term 		= $this->m_import_transaction->get_term_code($Term);
                                    $get_city 		= $this->m_import_transaction->get_am_city($City_Trouper);

                                    $City_DataBase_Trouper = strtoupper($get_city->CityName);

                                    if(empty($OldCustomerCode)){
                                            $result['message']  = 'Import Gagal Customer No Tidak Boleh Kosong';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(empty($CurrencyCode)){
                                            $result['message']  = 'Import Gagal Currency Code Tidak Boleh Kosong';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(empty($get_currency->CurrencyCode)){
                                            $result['message']  = 'Import Gagal Currency Code Tidak Ada Di Sistem';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(!empty($get_customer->OldCustomerCode)){
                                            $result['message']  = 'Import Gagal Customer Code '.$OldCustomerCode.' Sudah Ada Di Sistem';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(empty($get_city->CityName)){
                                            $result['message']  = 'Import Gagal Customer Name '.$CustomerName.', Wilayah/Kota'.$get_city->CityName.' Tidak Sama Dengan Di Sistem';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(empty($get_term)){
                                            $result['message']  = 'Import Gagal Customer Name '.$CustomerName.', Term '.$get_term.' Tidak Sama Dengan DI Sistem';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if($OldCustomerCode == $OldCustomerCode_1){
                                            $result['message']  = 'Import Gagal Duplicate Customer Code '.$OldCustomerCode.' Di Excel Silahkan Perbaiki';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if($BranchCode != $sess_branch		= $this->session->userdata('branch')){
                                            $result['message']  = 'Import Gagal Branch Excel Tidak Sama Dengan Branch Login';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    $OldCustomerCode_1 = $OldCustomerCode;
                            }

                            $sourceDate  		= date('Y-m-d');
                            $TransType 			= 'Customer';
                            $DataType 			= 'Insert';
                            $status 			= 1;

                            //$this->db->like('TransType', 'Item Inventories');
                    $num    = $this->db->get('ah_importtrans')->num_rows() + 1;

                            $this->db->like('TransType', 'Customer');
                    $number_data    = $this->db->get('ah_importtransdetail')->num_rows() + 1;

                            $data_hisimport = array(
                                    'ImportTransID' => $num,
                                    'TransType' 	=> $TransType, 
                                    'DataType' 		=> $DataType, 
                                    'ImportStatus' 	=> $status,
                                    'LastEdited' 	=> date('Y-m-d'),
                                    'LastUser' 		=> $this->session->userdata('username')
                            );

                            $this->db->trans_begin();
                            $insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
                            if($insert_result == 0) {$this->trans_rollback('insert');}

                            for($j=2;$j<=$lastRow;$j++){
                                    $sess_brach		= $this->session->userdata('branch');
                                    $ceknourut      = $this->m_customer->get_last_customer_code($sess_brach);

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

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

                                            $count_recnumb = strlen($pay_numb3);

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

                                            $branch = $sess_brach;
                                    }
                                    else{
                                            $branch = $sess_brach;
                                            $next_customer_numb 	= '0001';
                                    }

                                    $CustomerCode 	= $branch.'-'.$next_customer_numb;
                                    $OldCustomerCode = $sheetData[$j]['A'];
                                    $CustomerName 	= $sheetData[$j]['B'];
                                    $CurrencyCode 	= $sheetData[$j]['D'];
                                    $City 			= $sheetData[$j]['I'];
                                    $Province 		= $sheetData[$j]['J'];
                                    $ZipCode 		= $sheetData[$j]['K'];
                                    $Country 		= $sheetData[$j]['L'];
                                    $Fax 			= $sheetData[$j]['M'];
                                    $Email 			= $sheetData[$j]['N'];
                                    $WebPage 		= $sheetData[$j]['O'];
                                    $Tax1 			= $sheetData[$j]['P'];
                                    $Tax2 			= $sheetData[$j]['Q'];
                                    $TaxNumber 		= $sheetData[$j]['R'];
                                    $Pkp 			= $sheetData[$j]['S'];
                                    $Term 			= $sheetData[$j]['T'];
                                    $Memo 			= $sheetData[$j]['U'];
                                    $Wilayah 		= $sheetData[$j]['X'];
                                    $TaxType 		= $sheetData[$j]['Y'];
                                    $TaxAddres 		= $sheetData[$j]['Z'].' '.$sheetData[$j]['AA'];
                                    $BranchCode 	= $sheetData[$j]['AB'];

                                    $sourceDate  		= date('Y-m-d');
                                    $TransType 			= 'Customer';
                                    $DataType 			= 'Insert';
                                    $status 			= 1;

                                    ///ceking database	
                                    $get_currency 	= $this->m_import_transaction->get_currency_code($CurrencyCode);
                                    $get_city 		= $this->m_import_transaction->get_am_city($Wilayah);
                                    $state = $get_city->StateCode;

                                    $get_state 		= $this->m_import_transaction->get_am_state($state);
                                    $country_code 	= $get_state->CountryCode;

                                    $get_term 		= $this->m_import_transaction->get_term_code($Term);

                                    if(empty($Phone)){
                                            $Phone 	= 0;
                                    }
                                    else{
                                            $Phone 	= $sheetData[$j]['E'];
                                    }

                                    if(empty($ContactName)){
                                            $ContactName = "NA";
                                    }
                                    else{
                                            $ContactName = $sheetData[$j]['F'];
                                    }

                                    if(empty($Addres)){
                                            $Addres  = "NA";
                                    }
                                    else{
                                            $Addres  = $sheetData[$j]['G'].' '.$sheetData[$j]['H'];
                                    }

                                    $data = array(
                                            'BranchCode' 			=> $BranchCode,
                                            'CustomerCode' 			=> $CustomerCode,
                                            'OldCustomerCode' 		=> $OldCustomerCode,
                                            'CustomerName' 			=> $CustomerName,
                                            'CustomerAddress' 		=> $Addres,
                                            'CustTaxAddress' 		=> $TaxAddres,
                                            'CustomerCity' 			=> $get_city->CityCode,
                                            'CustomerState' 		=> $get_state->StateCode,
                                            'CustomerCountry' 		=> $country_code,
                                            'CustomerPostalCode' 	=> $ZipCode,
                                            'PhoneNumber' 			=> $Phone,
                                            'FacsimileNumber' 		=> $Fax,
                                            'ContactPerson' 		=> $ContactName,
                                            'EmailAddress' 			=> $Email,
                                            'WebAddress' 			=> $WebPage,
                                            'TermsPaymentID' 		=> $get_term,
                                            'CurrencyCode' 			=> $get_currency->CurrencyCode,
                                            'CurrencyMemo' 			=> $Memo,
                                            'Taxes1Code' 			=> $Tax1,
                                            'Taxes2Code' 			=> $Tax2,
                                            'TaxesNumber' 			=> $TaxNumber,
                                            'PPKPNumber' 			=> $Pkp,
                                            //'TaxesTypeID' 			=> ,
                                            'TransStatus' 			=> 1,
                                            'LastUser' 				=> $this->session->userdata('username')
                                    );

                                    $insert_result = $this->m_import_transaction->insert_am_customer($data);
                                    if($insert_result == 0) {$this->trans_rollback('insert');}

                                    $data_hisimport_detail = array(
                                            'BranchCode' 		=> $BranchCode,
                                            'ImportTransID' 	=> $num,
                                            'SourceNumber' 		=> $sheetData[$j]['A'],
                                            'TransType' 		=> $TransType, 
                                            'SourceDate' 		=> $sourceDate,
                                            'ImportNumber' 		=> $number_data,
                                            'LastUser' 			=> $this->session->userdata('username')
                                    );	

                                    $insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
                                    if($insert_result == 0) {$this->trans_rollback('insert');}

                            }
                    }
            }
            if ($insert_result === 0) {
                    $this->db->trans_rollback();
                    $result['status'] = false;
        $result['message'] = "Import Data Customer Gagal";			
            }
            else {
                    $this->db->trans_commit();
                    $result['status']   = true;
        $result['message'] = "Import Data Customer Berhasil";			
            }
            echo json_encode($result);
    }

    public function import_vendor(){
        try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];
            if($filename!=""&&$filename!=null){ //cek sudah pilih file yang diupload tidak..
                $objPHPExcel    = PHPExcel_IOFactory::load($filename);
                $objWriter      = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount     = $objPHPExcel->getSheetCount();

                //================ RULE BARU ==============================//
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();

                if( notCaseSensitifNotSpace($sheetData[1]['A'])==notCaseSensitifNotSpace("Vendor No") &&  //pengecekkan header huruf tidak case sensitif dan spasi tidak dipermasalahkan, jd saat pengecekkan menghilangkan spasi serta huruf dipaksa sama jenisnya(Upper/lower),yg dipakai sekarang upper. ini function diambil dari helper customstring_helper.php
                   notCaseSensitifNotSpace($sheetData[1]['B'])==notCaseSensitifNotSpace("Vendor Name") &&
                   notCaseSensitifNotSpace($sheetData[1]['C'])==notCaseSensitifNotSpace("Phone") &&
                   notCaseSensitifNotSpace($sheetData[1]['D'])==notCaseSensitifNotSpace("Contact Name") &&
                   notCaseSensitifNotSpace($sheetData[1]['E'])==notCaseSensitifNotSpace("Currency Name") &&
                   notCaseSensitifNotSpace($sheetData[1]['F'])==notCaseSensitifNotSpace("Type") &&
                   notCaseSensitifNotSpace($sheetData[1]['G'])==notCaseSensitifNotSpace("Address 1") &&
                   notCaseSensitifNotSpace($sheetData[1]['H'])==notCaseSensitifNotSpace("Address 2") &&
                   notCaseSensitifNotSpace($sheetData[1]['I'])==notCaseSensitifNotSpace("City") &&
                   notCaseSensitifNotSpace($sheetData[1]['J'])==notCaseSensitifNotSpace("Province") &&
                   notCaseSensitifNotSpace($sheetData[1]['K'])==notCaseSensitifNotSpace("Zip Code") &&
                   notCaseSensitifNotSpace($sheetData[1]['L'])==notCaseSensitifNotSpace("Country") &&
                   notCaseSensitifNotSpace($sheetData[1]['M'])==notCaseSensitifNotSpace("Fax") &&
                   notCaseSensitifNotSpace($sheetData[1]['N'])==notCaseSensitifNotSpace("E-mail") &&
                   notCaseSensitifNotSpace($sheetData[1]['O'])==notCaseSensitifNotSpace("Web Page") &&
                   notCaseSensitifNotSpace($sheetData[1]['P'])==notCaseSensitifNotSpace("Tax 1 Name") &&
                   notCaseSensitifNotSpace($sheetData[1]['Q'])==notCaseSensitifNotSpace("Tax 2 Name") &&
                   notCaseSensitifNotSpace($sheetData[1]['R'])==notCaseSensitifNotSpace("Tax Number") &&
                   notCaseSensitifNotSpace($sheetData[1]['S'])==notCaseSensitifNotSpace("PKP No") &&
                   notCaseSensitifNotSpace($sheetData[1]['T'])==notCaseSensitifNotSpace("Term Net Days") &&
                   notCaseSensitifNotSpace($sheetData[1]['U'])==notCaseSensitifNotSpace("Notes") &&
                   notCaseSensitifNotSpace($sheetData[1]['V'])==notCaseSensitifNotSpace("KATEGORI") &&
                   notCaseSensitifNotSpace($sheetData[1]['W'])==notCaseSensitifNotSpace("Tax Address 1") &&
                   notCaseSensitifNotSpace($sheetData[1]['X'])==notCaseSensitifNotSpace("Tax Address 2") &&
                   notCaseSensitifNotSpace($sheetData[1]['Y'])==notCaseSensitifNotSpace("Tax Type") &&
                   notCaseSensitifNotSpace($sheetData[1]['Z'])==notCaseSensitifNotSpace("GROUP") &&
                   notCaseSensitifNotSpace($sheetData[1]['AA'])==notCaseSensitifNotSpace("KATEGORI 2") &&
                   notCaseSensitifNotSpace($sheetData[1]['AB'])==notCaseSensitifNotSpace("Branch")
                ){                    
                    $dataImport = [];
                    $dataImport['data_hisimport']       = [];
                    $dataImport['data_hisimport_detail']= [];
                    $dataImport['data_cust']            = [];
                    $tempArrayCode                      = [];
                    $lastRowNoCode                      = 0;

                    $sourceDate     = date('Y-m-d');
                    $TransType      = 'Vendors';
                    $DataType       = 'Insert';
                    $status         = 1;		
                    $num            = $this->m_import_transaction->num_importtrans();
                    $number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
                    $data_hisimport = array(
                        'ImportTransID' => $num,
                        'TransType' 	=> $TransType, 
                        'DataType'      => $DataType, 
                        'ImportStatus' 	=> $status,
                        'LastEdited' 	=> date('Y-m-d'),
                        'LastUser'      => $this->session->userdata('username')
                    );
                    $dataImport['data_hisimport'][] = $data_hisimport;

                    for($i=2; $i<=$lastRow; $i++){
                        $OldVendorCode 	= upperNotSpace($sheetData[$i]['A']);
                        $VendorName 	= $sheetData[$i]['B'];
                        $CurrencyName 	= $sheetData[$i]['E'];
                        $City           = $sheetData[$i]['I'];
                        $Term           = $sheetData[$i]['T'];
                        $Kategori       = $sheetData[$i]['V'];
                        $Tax_Type       = $sheetData[$i]['Y'];
                        $BranchCode 	= upperNotSpace($sheetData[$i]['AB']);
                        $City_Trouper 	= strtoupper($City);

                        $Phone          = $sheetData[$i]['C'];
                        $ContactName 	= $sheetData[$i]['D'];
                        $Addres         = $sheetData[$i]['G'].''.$sheetData[$i]['H'];
                        $Wilayah        = $sheetData[$i]['I'];
                        $ZipCide        = $sheetData[$i]['K'];
                        $Fax            = $sheetData[$i]['M'];
                        $Email          = $sheetData[$i]['N'];
                        $WebPage        = $sheetData[$i]['O'];
                        $Tax1           = $sheetData[$i]['P'];
                        $Tax_Number     = $sheetData[$i]['R'];
                        $PKP_No         = $sheetData[$i]['S'];
                        $Notes          = $sheetData[$i]['U'];
                        $Tax_Addres     = $sheetData[$i]['W'].'-'.$sheetData[$i]['X'];
                        $Kategori       = $sheetData[$i]['V'];
                        $Tax1_Touper    = strtoupper($Tax1);

                        //ceking for tabel					
                        $get_currency 	= $this->m_import_transaction->get_currency_code($CurrencyName);
                        $get_city       = $this->m_import_transaction->get_am_city($City_Trouper);
                        //$get_city       = $this->m_import_transaction->get_am_city($Wilayah);
                        $state          = $get_city->StateCode;
                        $get_state      = $this->m_import_transaction->get_am_state($state);
                        $country_code 	= $get_state->CountryCode;	
                        $get_vendor 	= $this->m_import_transaction->get_vendor_code($BranchCode, $OldVendorCode);
                        $check_num_vendor       = $this->m_import_transaction->check_num_vendor_code($BranchCode, $OldVendorCode);
                        $check_num_oldvendor    = $this->m_import_transaction->check_num_oldvendor_code($BranchCode, $OldVendorCode);
                        $get_tax_type 	= $this->m_import_transaction->get_tax_type_vendor($Tax_Type);

                        if((notCaseSensitifNotSpace($OldVendorCode)==null || notCaseSensitifNotSpace($OldVendorCode)=="") &&
                            (notCaseSensitifNotSpace($VendorName)==null || notCaseSensitifNotSpace($VendorName)=="") &&
                            (notCaseSensitifNotSpace($CurrencyName)==null || notCaseSensitifNotSpace($CurrencyName)=="") &&
                            (notCaseSensitifNotSpace($City)==null || notCaseSensitifNotSpace($City)=="") &&
                            (notCaseSensitifNotSpace($Term)==null || notCaseSensitifNotSpace($Term)=="") &&
                            (notCaseSensitifNotSpace($Kategori)==null || notCaseSensitifNotSpace($Kategori)=="") &&
                            (notCaseSensitifNotSpace($Tax_Type)==null || notCaseSensitifNotSpace($Tax_Type)=="") &&
                            (notCaseSensitifNotSpace($BranchCode)==null || notCaseSensitifNotSpace($BranchCode)=="")
                        ){
                            //kosong semua skip
                        }
                        else if(notCaseSensitifNotSpace($OldVendorCode)==null || notCaseSensitifNotSpace($OldVendorCode)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Vendor No","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(notCaseSensitifNotSpace($VendorName)==null || notCaseSensitifNotSpace($VendorName)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Vendor Name","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(notCaseSensitifNotSpace($CurrencyName)==null || notCaseSensitifNotSpace($CurrencyName)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Currency","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        /*else if(notCaseSensitifNotSpace($City)==null || notCaseSensitifNotSpace($City)==""){
                            throw new Exception(noticesImport("denied",["column"=>"City","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        } */
                        else if(notCaseSensitifNotSpace($BranchCode)==null || notCaseSensitifNotSpace($BranchCode)==""){
                            throw new Exception(noticesImport("denied",["column"=>"BranchCode","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }   
                        else if($BranchCode != $sess_branch		= $this->session->userdata('branch')){
                            throw new Exception(noticesImport("notMatchLogin", ["column"=>"Branch","code"=>$BranchCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        /*else if(notCaseSensitifNotSpace($get_city->CityName)==null || notCaseSensitifNotSpace($get_city->CityName)==""){
                            throw new Exception(noticesImport("notfound", ["column"=>"City","code"=>$City,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }*/
                        else if(empty($get_currency->CurrencyCode)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Currency Code","code"=>$CurrencyName,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if($check_num_vendor){
                            throw new Exception(noticesImport("sameInTable", ["column"=>"Vendor Code","code"=>$OldVendorCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if($check_num_oldvendor){
                            throw new Exception(noticesImport("sameInTable", ["column"=>"Old Vendor Code","code"=>$OldVendorCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(in_array($OldVendorCode, $tempArrayCode)){
                            throw new Exception(noticesImport("duplicate", ["column"=>"Vendor Code","code"=>$OldVendorCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
    //                        else if(empty($get_term)){
    //                            $result['status']   = false;
    //                            $result['message']  = noticesImport("notfound", ["column"=>"Term","code"=>$get_term,"di"=>"Sistem","line"=>$i]);//pesan yang diambil dr helper : notices_import_file_helper.php
    //                            echo json_encode($result);
    //                            die();
    //                        } 
                        else if(notCaseSensitifNotSpace($Tax_Type)==null || notCaseSensitifNotSpace($Tax_Type)==""){
                            throw new Exception(noticesImport("denied",["column"=>"Tax Type","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(empty($get_tax_type->TaxTypeName)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Tax Type","code"=>$Tax_Type,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else{                            
                            $tempArrayCode[]= $OldVendorCode;

                            if(($Tax1_Touper != 'PPN') && ($Tax1_Touper != 'PPN EFEKTIF')){
                                $pajak = NULL;
                            }else{
                                if($Tax1_Touper == 'PPN'){
                                    $Tax_name = 'PAJAK PERTAMBAHAN NILAI';
                                }else{
                                    $Tax_name = $Tax1_Touper;
                                }
                                $Ppn        = $Tax_name;
                                $get_taxes  = $this->m_import_transaction->taxes($Ppn);
                                $pajak      = $get_taxes->TaxesCode;
                            }

                            if(notCaseSensitifNotSpace($Term)==null || (notCaseSensitifNotSpace($Term)=="") || (notCaseSensitifNotSpace($Term)<0) ){//jika term "" ato null ato krg dari 0, maka dikasih nilai 0
                                $Term = 0;
                            } 
                            $get_term       = $this->m_import_transaction->get_term_code($Term);

                            if(notCaseSensitifNotSpace($Phone)==null || notCaseSensitifNotSpace($Phone)==""){
                                $Phone 	= 0;
                            }

                            if(notCaseSensitifNotSpace($ContactName)==null || notCaseSensitifNotSpace($ContactName)==""){
                                $ContactName = "NA";
                            }

                            if(notCaseSensitifNotSpace($Addres)==null || notCaseSensitifNotSpace($Addres)==""){
                                $Addres  = "NA";
                            }

                            if(notCaseSensitifNotSpace($ZipCide)==null || notCaseSensitifNotSpace($ZipCide)==""){
                                $ZipCide = 0;
                            }

                            $sess_brach = $this->session->userdata('branch');		
                            $ceknourut  = $this->m_vendors->get_last_vendor_code($BranchCode);

                            if($lastRowNoCode>0){
                                $lastRowNoCode = $lastRowNoCode + 1;
                                $pay_numb3     = $lastRowNoCode;
                                $count_recnumb = strlen($pay_numb3);
                                if($count_recnumb == 1){
                                        $next_vendor_numb = '00'.$pay_numb3;
                                }elseif($count_recnumb == 2){
                                        $next_vendor_numb = '0'.$pay_numb3;
                                }elseif($count_recnumb == 3){
                                        $next_vendor_numb = $pay_numb3;
                                }
                                $branch_param1 = $BranchCode;
                            }else{
                                if(!empty($ceknourut) || $ceknourut != null){
                                    foreach($ceknourut as $row){
                                        $number         = $row->VendorCode;
                                        $explode_number	= explode("-", $number);
                                        $last_index     = (count($explode_number) -1);
                                        $last_number    = $explode_number[$last_index];

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

                                    $count_recnumb = strlen($pay_numb3);
                                    if($count_recnumb == 1){
                                            $next_vendor_numb = '00'.$pay_numb3;
                                    }elseif($count_recnumb == 2){
                                            $next_vendor_numb = '0'.$pay_numb3;
                                    }elseif($count_recnumb == 3){
                                            $next_vendor_numb = $pay_numb3;
                                    }
                                    $branch_param1 = $BranchCode;
                                }else{
                                    $lastRowNoCode = 1;
                                    $branch_param1 = $BranchCode;
                                    $next_vendor_numb 	= '001';
                                }
                            }
                            $VendorCode 	= $branch_param1.'-'.$next_vendor_numb;
                            $data_vendor = array(
                                    'BranchCode' 		=> $BranchCode,
                                    'VendorCode' 		=> $VendorCode,
                                    'OldVendorCode' 	=> $OldVendorCode,
                                    'VendorName' 		=> $VendorName.' '.$get_currency->CurrencyCode,
                                    'VendorAddress' 	=> $Addres,
                                    'VendorTaxAddress' 	=> $Tax_Addres,
                                    'VendorCity' 		=> $get_city->CityCode,
                                    'VendorState' 		=> $get_state->StateCode,
                                    'VendorCountry' 	=> $country_code,
                                    'VendorPostalCode' 	=> $ZipCide,
                                    'PhoneNumber' 		=> $Phone,
                                    'FacsimileNumber' 	=> $Fax,
                                    'ContactPerson' 	=> $ContactName,
                                    'EmailAddress' 		=> $Email,
                                    'WebAddress' 		=> $WebPage,
                                    'VendorCategory' 	=> $Kategori,
                                    'VendorNotes' 		=> $Notes,
                                    'TermsPaymentID' 	=> $get_term,
                                    'CurrencyCode' 		=> $get_currency->CurrencyCode,
                                    'Tax1Code' 			=> $pajak,
                                    'VendorTaxNumber' 	=> $Tax_Number,
                                    'TaxTypeID'			=> $get_tax_type->TaxTypeID ,
                                    'PKPNumber' 		=> $PKP_No,
                                    'VendorStatus' 		=> 0,
                                    'TransStatus' 		=> 1,
                                    'LastUser' 			=> $this->session->userdata('username')
                            );					
                            //$insert_result = $this->m_import_transaction->insert_am_vendor($data);
                            $dataImport['data_vendor'][] = $data_vendor;

                            $data_hisimport_detail = array(
                                    'BranchCode' 		=> $BranchCode,
                                    'ImportTransID' 	=> $num,
                                    'SourceNumber' 		=> $VendorCode,
                                    'TransType' 		=> $TransType, 
                                    'SourceDate' 		=> $sourceDate,
                                    'ImportNumber' 		=> $number_data,
                                    'LastUser' 			=> $this->session->userdata('username')
                            );	
    //                            $insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
                            $dataImport['data_hisimport_detail'][] = $data_hisimport_detail;
                        }
                    }

                    $rstImport = $this->m_import_transaction->importVendorMaster($dataImport);
                    if($rstImport){
                        $result['status']   = true;
                        $result['message']  = get_notification('insert', 1);
                        //$result['message']  = noticesImport("success",[]);
                    }else{
                        $result['status']   = false;
                        $result['message']  = get_notification('insert', 0);
                        //$result['message']  = noticesImport("failed",[]);
                    }      
                    echo json_encode($result);              
                }
                else if( notCaseSensitifNotSpace($sheetData[1]['A'])!=notCaseSensitifNotSpace("Vendor No")){ 
                    throw new Exception(noticesImport("notCell",["column"=>"Vendor No","code"=>"A1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if(notCaseSensitifNotSpace($sheetData[1]['B'])!=notCaseSensitifNotSpace("Vendor Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Vendor Name","code"=>"B1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['C'])!=notCaseSensitifNotSpace("Phone")){
                    throw new Exception(noticesImport("notCell",["column"=>"Phone","code"=>"C1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['D'])!=notCaseSensitifNotSpace("Contact Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Contact Name","code"=>"D1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['E'])!=notCaseSensitifNotSpace("Currency Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Currency Name","code"=>"E1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['F'])!=notCaseSensitifNotSpace("Type")){
                    throw new Exception(noticesImport("notCell",["column"=>"Type","code"=>"F1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['G'])!=notCaseSensitifNotSpace("Address 1")){
                    throw new Exception(noticesImport("notCell",["column"=>"Address 1","code"=>"G1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['H'])!=notCaseSensitifNotSpace("Address 2")){
                    throw new Exception(noticesImport("notCell",["column"=>"Address 2","code"=>"H1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['I'])!=notCaseSensitifNotSpace("City")){
                    throw new Exception(noticesImport("notCell",["column"=>"City","code"=>"I1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['J'])!=notCaseSensitifNotSpace("Province")){
                    throw new Exception(noticesImport("notCell",["column"=>"Province","code"=>"J1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['K'])!=notCaseSensitifNotSpace("Zip Code")){
                    throw new Exception(noticesImport("notCell",["column"=>"Zip Code","code"=>"K1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['L'])!=notCaseSensitifNotSpace("Country")){
                    throw new Exception(noticesImport("notCell",["column"=>"Country","code"=>"L1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['M'])!=notCaseSensitifNotSpace("Fax")){
                    throw new Exception(noticesImport("notCell",["column"=>"Fax","code"=>"M1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['N'])!=notCaseSensitifNotSpace("E-mail")){
                    throw new Exception(noticesImport("notCell",["column"=>"E-mail","code"=>"N1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['O'])!=notCaseSensitifNotSpace("Web Page")){
                    throw new Exception(noticesImport("notCell",["column"=>"Web Page","code"=>"O1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['P'])!=notCaseSensitifNotSpace("Tax 1 Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Tax 1 Name","code"=>"P1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['Q'])!=notCaseSensitifNotSpace("Tax 2 Name")){
                    throw new Exception(noticesImport("notCell",["column"=>"Tax 2 Name","code"=>"Q1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['R'])!=notCaseSensitifNotSpace("Tax Number")){
                    throw new Exception(noticesImport("notCell",["column"=>"Tax Number","code"=>"R1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['S'])!=notCaseSensitifNotSpace("PKP No")){
                    throw new Exception(noticesImport("notCell",["column"=>"PKP No","code"=>"S1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['T'])!=notCaseSensitifNotSpace("Term Net Days")){
                    throw new Exception(noticesImport("notCell",["column"=>"Term Net Days","code"=>"T1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['U'])!=notCaseSensitifNotSpace("Notes")){
                    throw new Exception(noticesImport("notCell",["column"=>"Notes","code"=>"U1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['V'])!=notCaseSensitifNotSpace("KATEGORI")){
                    throw new Exception(noticesImport("notCell",["column"=>"Kategori","code"=>"V1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['W'])!=notCaseSensitifNotSpace("Tax Address 1")){
                    throw new Exception(noticesImport("notCell",["column"=>"Tax Address 1","code"=>"W1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['X'])!=notCaseSensitifNotSpace("Tax Address 2")){
                    throw new Exception(noticesImport("notCell",["column"=>"Tax Address 2","code"=>"X1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['Y'])!=notCaseSensitifNotSpace("Tax Type")){
                    throw new Exception(noticesImport("notCell",["column"=>"Tax Type","code"=>"Y1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['Z'])!=notCaseSensitifNotSpace("GROUP")){
                    throw new Exception(noticesImport("notCell",["column"=>"GROUP","code"=>"Z1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['AA'])!=notCaseSensitifNotSpace("KATEGORI 2")){
                    throw new Exception(noticesImport("notCell",["column"=>"Kategori 2","code"=>"AA1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if (notCaseSensitifNotSpace($sheetData[1]['AB'])!=notCaseSensitifNotSpace("Branch")){
                    throw new Exception(noticesImport("notCell",["column"=>"Branch","code"=>"AB1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }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);
        }
    }
    public function import_vendorLAMA(){
		ini_set("max_execution_time", 'time_limit');
		ini_set('memory_limit', '1024M'); //your memory limit as string
		include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
		$filename = $_FILES['uploadfile']['tmp_name'];
		$objPHPExcel = PHPExcel_IOFactory::load($filename);
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
		$sheetCount = $objPHPExcel->getSheetCount();
		for($i=0; $i<=$sheetCount; $i++) {		
			if($i == 0){
				$objPHPExcel->setActiveSheetIndex($i);
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();  
				
				/*foreach ($cell_collection as $cell) {  
					$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();  
    				$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();  
    				$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue(); 
					if ($row == 1) {  
						$header[$row][$columns] = $data_value;  
					} 
					
					
					
					echo $columns.'<br>';
					die();
					if($header[$row][$columns] != 'Vendor No'){
						$result['message']  = 'Cell A1 Ini Bukan Vendor No';
						$result['status']   = false;
							
						echo json_encode($result);
						
					}
				}*/
				for($l=1; $l<=$lastRow; $l++){
					if($sheetData[1]['A'] != 'Vendor No'){
						$result['message']  = 'Cell A1 Ini Bukan Vendor No';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['B'] != 'Vendor Name'){
						$result['message']  = 'Cell B1 Ini Bukan Vendor Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['C'] != 'Phone'){
						$result['message']  = 'Cell C1 Ini Bukan Phone';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['D'] != 'Contact Name'){
						$result['message']  = 'Cell D1 Ini Bukan Contact Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['E'] != 'Currency Name'){
						$result['message']  = 'Cell E1 Ini Bukan Currency Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['F'] != 'Type'){
						$result['message']  = 'Cell F1 Ini Bukan Type';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['G'] != 'Address 1'){
						$result['message']  = 'Cell G1 Ini Bukan Address 1';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['H'] != 'Address 2'){
						$result['message']  = 'Cell H1 Ini Bukan Address 2';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['I'] != 'City'){
						$result['message']  = 'Cell I1 Ini Bukan City';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['J'] != 'Province'){
						$result['message']  = 'Cell J1 Ini Bukan Province';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['K'] != 'Zip Code'){
						$result['message']  = 'Cell K1 Ini Bukan Zip Code';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['L'] != 'Country'){
						$result['message']  = 'Cell L1 Ini Bukan Country';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['M'] != 'Fax'){
						$result['message']  = 'Cell M1 Ini Bukan Fax';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['N'] != 'E-mail'){
						$result['message']  = 'Cell N1 Ini Bukan E-mail';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['O'] != 'Web Page'){
						$result['message']  = 'Cell O1 Ini Bukan Web Page';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['P'] != 'Tax 1 Name'){
						$result['message']  = 'Cell P1 Ini Bukan Tax 1 Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['Q'] != 'Tax 2 Name'){
						$result['message']  = 'Cell Q1 Ini Bukan Tax 2 Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['R'] != 'Tax Number'){
						$result['message']  = 'Cell R1 Ini Bukan Tax Number';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['S'] != 'PKP No'){
						$result['message']  = 'Cell S1 Ini Bukan PKP No';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['T'] != 'Term Net Days'){
						$result['message']  = 'Cell T1 Ini Bukan Term Net Days';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['U'] != 'Notes'){
						$result['message']  = 'Cell U1 Ini Bukan Notes';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['V'] != 'KATEGORI'){
						$result['message']  = 'Cell V1 Ini Bukan KATEGORI';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['W'] != 'Tax Address 1'){
						$result['message']  = 'Cell W1 Ini Bukan Tax Address 1';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['X'] != 'Tax Address 2'){
						$result['message']  = 'Cell X1 Ini Bukan Tax Address 2';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['Y'] != 'Tax Type'){
						$result['message']  = 'Cell Y1 Ini Bukan Tax Type';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['Z'] != 'GROUP'){
						$result['message']  = 'Cell Z1 Ini Bukan GROUP';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['AA'] != 'KATEGORI 2'){
						$result['message']  = 'Cell AA Ini Bukan KATEGORI 2';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['AB'] != 'Branch'){
						$result['message']  = 'Cell AB1 Ini Bukan Branch';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
				}
				
				$OldVendorCode_1 = '';
				
				for($h=2; $h<=$lastRow; $h++){
					
					$OldVendorCode 	= $sheetData[$h]['A'];
					$CurrencyName 	= $sheetData[$h]['E'];
					$City 			= $sheetData[$h]['I'];
					$City_Trouper 	= strtoupper($City);
					$VendorName 	= $sheetData[$h]['B'];
					$BranchCode 	= $sheetData[$h]['AB'];
					$Term 			= $sheetData[$h]['T'];
					$Tax_Type		= $sheetData[$h]['Y'];
					$Kategori		= $sheetData[$h]['V'];
					
					$get_currency 	= $this->m_import_transaction->get_currency_code($CurrencyName);
					$get_city 		= $this->m_import_transaction->get_am_city($City_Trouper);
					$get_vendor 	= $this->m_import_transaction->get_vendor_code($BranchCode, $OldVendorCode);
					$get_tax_type 	= $this->m_import_transaction->get_tax_type_vendor($Tax_Type);
					
					$get_term 		= $this->m_import_transaction->get_term_code($Term);
					
					if(empty($OldVendorCode)){
						$result['message']  = 'Import Gagal Vendor No Tidak Boleh Kosong';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($CurrencyName)){
						$result['message']  = 'Import Gagal Currency Tidak Boleh Kosong';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_currency->CurrencyCode)){
						$result['message']  = 'Import Gagal Currency '.$CurrencyName.' Tidak Ada Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_city->CityName)){
						$result['message']  = 'Import Gagal Vendor Name '.$VendorName.', Kota'.$get_city->CityName.' Tidak Sama Dengan Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(!empty($get_vendor->OldVendorCode)){
						$result['message']  = 'Import Gagal Vendor Code '.$OldVendorCode.' Sudah Ada Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if($OldVendorCode == $OldVendorCode_1){
						$result['message']  = 'Import Gagal Duplicate Vendor Code '.$OldVendorCode.' Di Excel Silahkan Perbaiki';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_term)){
						$result['message']  = 'Import Gagal Vendor Name '.$VendorName.', Term '.$get_term.' Tidak Sama Dengan Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_tax_type->TaxTypeName)){
						$result['message']  = 'Import Gagal Vendor Name '.$VendorName.', Tax Type '.$Tax_Type.' Tidak Sama Dengan Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}/*
					else if($BranchCode != $sess_branch		= $this->session->userdata('branch')){
						$result['message']  = 'Import Gagal Branch Excel Tidak Sama Dengan Branch Login';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					*/
					$OldVendorCode_1 = $OldVendorCode;
				}
				
				$sourceDate  		= date('Y-m-d');
				$TransType 			= 'Vendors';
				$DataType 			= 'Insert';
				$status 			= 1;
		
				//$this->db->like('TransType', 'Item Inventories');
           		$num    = $this->db->get('ah_importtrans')->num_rows() + 1;
				
				$this->db->like('TransType', 'Vendors');
           		$number_data    = $this->db->get('ah_importtransdetail')->num_rows() + 1;
				
				$data_hisimport = array(
					'ImportTransID' => $num,
					'TransType' 	=> $TransType, 
					'DataType' 		=> $DataType, 
					'ImportStatus' 	=> $status,
					'LastEdited' 	=> date('Y-m-d'),
					'LastUser' 		=> $this->session->userdata('username')
				);
				
				$this->db->trans_begin();
				$insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
				if($insert_result == 0) {$this->trans_rollback('insert');}
				
				for($j=2;$j<=$lastRow;$j++){
					//new variabel
					$OldVendorCode 	= $sheetData[$j]['A'];
					$VendorName 	= $sheetData[$j]['B'];
					$Phone 			= $sheetData[$j]['C'];
					$ContactName 	= $sheetData[$j]['D'];
					$CurrencyName 	= $sheetData[$j]['E'];
					$Addres 		= $sheetData[$j]['G'].''.$sheetData[$j]['H'];
					$Wilayah 		= $sheetData[$j]['I'];
					$ZipCide 		= $sheetData[$j]['K'];
					$Fax	 		= $sheetData[$j]['M'];
					$Email	 		= $sheetData[$j]['N'];
					$WebPage	 	= $sheetData[$j]['O'];
					$Tax1		 	= $sheetData[$j]['P'];
					$Tax_Number		= $sheetData[$j]['R'];
					$PKP_No			= $sheetData[$j]['S'];
					$Term			= $sheetData[$j]['T'];
					$Notes			= $sheetData[$j]['U'];
					$Tax_Type		= $sheetData[$j]['Y'];
					$Tax_Addres		= $sheetData[$j]['W'].'-'.$sheetData[$j]['X'];
					$Kategori		= $sheetData[$j]['V'];
					$BranchCode		= $sheetData[$j]['AB'];
					
					$sourceDate  		= date('Y-m-d');
					$TransType 			= 'Vendors';
					$DataType 			= 'Insert';
					$status 			= 1;
					
					$Tax1_Touper = strtoupper($Tax1);
					
					//end new variabel
					
					//ceking for tabel
					$get_city 		= $this->m_import_transaction->get_am_city($Wilayah);
					$state 			= $get_city->StateCode;
					
					$get_state 		= $this->m_import_transaction->get_am_state($state);
					$country_code 	= $get_state->CountryCode;
					
					$get_term 		= $this->m_import_transaction->get_term_code($Term);
					$get_currency 	= $this->m_import_transaction->get_currency_code($CurrencyName);
					
					$get_tax_type 	= $this->m_import_transaction->get_tax_type_vendor($Tax_Type);
					
					if(($Tax1_Touper != 'PPN') && ($Tax1_Touper != 'PPN EFEKTIF')){
						$pajak = NULL;
					}
					else{
						if($Tax1_Touper == 'PPN'){
							$Tax_name = 'PAJAK PERTAMBAHAN NILAI';
						}
						else{
							$Tax_name = $Tax1_Touper;
						}
					
						$Ppn = $Tax_name;
						$get_taxes 		= $this->m_import_transaction->taxes($Ppn);
						$pajak = $get_taxes->TaxesCode;
					}
					
					if(empty($Phone)){
						$Phone 	= 0;
					}
					else{
						$Phone 	= $sheetData[$j]['C'];
					}
					
					if(empty($ContactName)){
						$ContactName = "NA";
					}
					else{
						$ContactName = $sheetData[$j]['D'];
					}
					
					if(empty($Addres)){
						$Addres  = "NA";
					}
					else{
						$Addres  = $sheetData[$j]['G'].''.$sheetData[$j]['H'];
					}
					
					if($ZipCide == ''){
						$ZipCide = 0;
					}
					else{
						$ZipCide = $ZipCide;
					}
					//end ceking
					
					$sess_brach		= $this->session->userdata('branch');		
					$ceknourut= $this->m_vendors->get_last_vendor_code($BranchCode);
				
					if(!empty($ceknourut) || $ceknourut != null){
						foreach($ceknourut as $row){
							$number         = $row->VendorCode;
							$explode_number	= explode("-", $number);
							$last_index     = (count($explode_number) -1);
							$last_number    = $explode_number[$last_index];
			
							if(empty($last_index)){
								$pay_numb3	= '001';
							}
							else {
								$pay_numb3	= $last_number+1;
							}
						}
						
						$count_recnumb = strlen($pay_numb3);
				
						if($count_recnumb == 1){
							$next_vendor_numb = '00'.$pay_numb3;
						}
						elseif($count_recnumb == 2){
							$next_vendor_numb = '0'.$pay_numb3;
						}
						elseif($count_recnumb == 3){
							$next_vendor_numb = $pay_numb3;
						}
						
						$branch_param1 = $BranchCode;
					}
					else{
						$branch_param1 = $BranchCode;
						$next_vendor_numb 	= '001';
					}
					
					$VendorCode 	= $branch_param1.'-'.$next_vendor_numb;
					
					$data = array(
						'BranchCode' 		=> $BranchCode,
						'VendorCode' 		=> $VendorCode,
						'OldVendorCode' 	=> $OldVendorCode,
						'VendorName' 		=> $VendorName,
						'VendorAddress' 	=> $Addres,
						'VendorTaxAddress' 	=> $Tax_Addres,
						'VendorCity' 		=> $get_city->CityCode,
						'VendorState' 		=> $get_state->StateCode,
						'VendorCountry' 	=> $country_code,
						'VendorPostalCode' 	=> $ZipCide,
						'PhoneNumber' 		=> $Phone,
						'FacsimileNumber' 	=> $Fax,
						'ContactPerson' 	=> $ContactName,
						'EmailAddress' 		=> $Email,
						'WebAddress' 		=> $WebPage,
						'VendorCategory' 	=> $Kategori,
						'VendorNotes' 		=> $Notes,
						'TermsPaymentID' 	=> $get_term,
						'CurrencyCode' 		=> $get_currency->CurrencyCode,
						'Tax1Code' 			=> $pajak,
						'VendorTaxNumber' 	=> $Tax_Number,
						'TaxTypeID'			=> $get_tax_type->TaxTypeID ,
						'PKPNumber' 		=> $PKP_No,
						'VendorStatus' 		=> 0,
						'TransStatus' 		=> 1,
						'LastUser' 			=> $this->session->userdata('username')
					);
					
					$insert_result = $this->m_import_transaction->insert_am_vendor($data);
					if($insert_result == 0) {$this->trans_rollback('insert');}
					
					$data_hisimport_detail = array(
						'BranchCode' 		=> $BranchCode,
						'ImportTransID' 	=> $num,
						'SourceNumber' 		=> $VendorCode,
						'TransType' 		=> $TransType, 
						'SourceDate' 		=> $sourceDate,
						'ImportNumber' 		=> $number_data,
						'LastUser' 			=> $this->session->userdata('username')
					);	
					
					$insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
					if($insert_result == 0) {$this->trans_rollback('insert');}
				}
			}
		}
		if ($insert_result === 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
            $result['message'] = "Import data vendor gagal";			
		}
		else {
			$this->db->trans_commit();
			 $result['status']   = true;
             $result['message'] = "Import data vendor berhasil";			
		}
		echo json_encode($result);
	}
	
	public function import_purchase_requisition(){
		ini_set("max_execution_time", 'time_limit');
		ini_set('memory_limit', '1024M'); //your memory limit as string
		include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
		$filename = $_FILES['uploadfile']['tmp_name'];
		$objPHPExcel = PHPExcel_IOFactory::load($filename);
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
		$sheetCount = $objPHPExcel->getSheetCount();
		for($i=0; $i<=$sheetCount; $i++) {		
			if($i == 0){
				$objPHPExcel->setActiveSheetIndex($i);
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
				
				for($l=1; $l<=$lastRow; $l++){
					if($sheetData[1]['A'] != 'Request No.'){
						$result['message']  = 'Cell A1 Ini Bukan Request No.';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['B'] != 'Request Date'){
						$result['message']  = 'Cell B1 Ini Bukan Request Date';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['C'] != 'Item No.'){
						$result['message']  = 'Cell C1 Ini Bukan Phone';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['D'] != 'Item Description'){
						$result['message']  = 'Cell D1 Ini Bukan Item Description';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['E'] != 'Quantity'){
						$result['message']  = 'Cell E1 Ini Bukan Quantity';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['F'] != 'Unit'){
						$result['message']  = 'Cell F1 Ini Bukan Unit';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['G'] != 'Qty. Ord.'){
						$result['message']  = 'Cell G1 Ini Bukan Qty. Ord.';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['H'] != 'Qty. Recvd.'){
						$result['message']  = 'Cell H1 Ini Bukan Qty. Recvd.';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['I'] != 'Description'){
						$result['message']  = 'Cell I1 Ini Bukan Description';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['J'] != 'Required Date'){
						$result['message']  = 'Cell J1 Ini Bukan Required Date';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['K'] != 'Notes'){
						$result['message']  = 'Cell K1 Ini Bukan Notes';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['L'] != 'Dept. Name'){
						$result['message']  = 'Cell L1 Ini Bukan Dept. Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['M'] != 'Status'){
						$result['message']  = 'Cell M1 Ini Bukan Status';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['N'] != 'Branch'){
						$result['message']  = 'Cell N1 Ini Bukan Branch';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					
				}
				
				//ceking data preq
				for($h=2;$h<=$lastRow;$h++){
					$Department 	= $sheetData[$h]['L'];
					$BranchCode 	= $sheetData[$h]['N'];
					$OldPreqNumber 	= $sheetData[$h]['A'];
					$ItemCode 	 	= $sheetData[$h]['C'];
					$ItemDesc 	 	= $sheetData[$h]['D'];
					
					$Department_Touper = strtoupper($Department);
					
					$get_department = $this->m_import_transaction->get_departemen_code_name($Department_Touper);
					
					$get_item_code  		= $this->m_import_transaction->get_item_by_desc($ItemDesc);
					$get_item_sys_service  	= $this->m_import_transaction->get_item_sys_servis($ItemDesc);
					
					
					if(empty($Department)){
						$result['message']  = 'Import Gagal Department Tidak Boleh Kosong';
						$result['status']   = false;
						$this->db->trans_rollback();
						echo json_encode($result);
						die();
					}
					else if(empty($get_department->DepartmentName)){
						$result['message']  = 'Import Gagal Department Name '.$DepartmentName.',  Tidak Sama Dengan Di Sistem';
						$result['status']   = false;
						$this->db->trans_rollback();
						echo json_encode($result);
						die();
					}
					else if(empty($OldPreqNumber)){
						$result['message']  = 'Import Gagal Preq No Tidak Boleh Kosong Di Excel';
						$result['status']   = false;
						$this->db->trans_rollback();
						echo json_encode($result);
						die();
					}
					else if(empty($get_item_code->ItemDesc)){
						if(empty($get_item_sys_service->SvcDetailName)){							
							$result['message']  = 'Import Gagal Item '.$ItemDesc.' Tidak Ada Di Sistem (Item Inventory Maupun Non Inventory)';
							$result['status']   = false;
							$this->db->trans_rollback();
							echo json_encode($result);
							die();
						}
					}
					else if($BranchCode != $sess_branch	= $this->session->userdata('branch')){
						$result['message']  = 'Import Gagal Branch Excel Tidak Sama Dengan Branch Login';
						$result['status']   = false;
						$this->db->trans_rollback();
						echo json_encode($result);
						die();
					}
				}
				//end ceking preq
				$OldPReqNumber_1 = '';
				
				$sourceDate  		= date('Y-m-d');
				$TransType 			= 'PR';
				$DataType 			= 'Insert';
				$status 			= 1;
		
				//$this->db->like('TransType', 'Item Inventories');
           		$num    = $this->db->get('ah_importtrans')->num_rows() + 1;
				
				$this->db->like('TransType', 'Purchase Requisition');
           		$number_data    = $this->db->get('ah_importtransdetail')->num_rows() + 1;
				
				$data_hisimport = array(
					'ImportTransID' => $num,
					'TransType' 	=> $TransType, 
					'DataType' 		=> $DataType, 
					'ImportStatus' 	=> $status,
					'LastEdited' 	=> date('Y-m-d'),
					'LastUser' 		=> $this->session->userdata('username')
				);
				
				$this->db->trans_begin();
				$insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
				//if($insert_result == false) {$this->trans_rollback('insert');}
				
				for($j=2;$j<=$lastRow;$j++){
					$OldPReqNumber  = $sheetData[$j]['A'];
					$Department  = $sheetData[$j]['L'];
					$ItemCode  	 = $sheetData[$j]['C'];
					$ItemDesc  	 = $sheetData[$j]['D'];
					$branch_code = $sheetData[$j]['N'];
					
					$sourceDate  		= date('Y-m-d');
					$DataType 			= 'Insert';
					$status 			= 1;
					
					$Department_Touper = strtoupper($Department);
					
					$get_department = $this->m_import_transaction->get_departemen_code_name($Department_Touper);
					$get_item_code  = $this->m_import_transaction->get_item_by_desc($ItemDesc);
					
					$get_item_sys_service  	= $this->m_import_transaction->get_item_sys_servis($ItemDesc);
					if($get_item_code != FALSE){
						$item_master_code = $get_item_code->ItemCode;
						$item_master_desc = $get_item_code->ItemDesc;
						$item_master_unit = $get_item_code->ItemUnit;
						$item_master_category_id = $get_item_code->ItemCategoryID;
						$item_master_category_name = $get_item_code->ItemCategoryName;
						$ItemType = 0;
						$ItemStatus = 0;
					}
					else if($get_item_sys_service != FALSE){
						$item_master_code = $get_item_sys_service->SvcDetailName;
						$item_master_desc = $get_item_sys_service->SvcDetailDesc;
						$item_master_unit = $get_item_sys_service->SvcDetailUnit;
						$item_master_category_id = $get_item_sys_service->SvcCategoryID;
						$item_master_category_name = $get_item_sys_service->SvcDetailName;
						$ItemType = 1;
						$ItemStatus = 2;
					}
					else {
						$result['message']  = 'Import Gagal Item '.$ItemDesc.' Tidak Ada Di Sistem (Item Inventory Maupun Non Inventory)';
						$result['status']   = false;
						$this->db->trans_rollback();
						echo json_encode($result);
						die();
					}
					//preq date convert
					$Time_Preq 	= explode(" ",$sheetData[$j]['B']);
					
					if($Time_Preq[1] == 'Jan'){
						$Bulan = '01';
					}
					else if($Time_Preq[1] == 'Feb'){
						$Bulan = '02';
					}
					else if($Time_Preq[1] == 'Mar'){
						$Bulan = '03';
					}
					else if($Time_Preq[1] == 'Apr'){
						$Bulan = '04';
					}
					else if($Time_Preq[1] == 'Mei'){
						$Bulan = '05';
					}
					else if($Time_Preq[1] == 'Jun'){
						$Bulan = '06';
					}
					else if($Time_Preq[1] == 'Jul'){
						$Bulan = '07';
					}
					else if($Time_Preq[1] == 'Aug'){
						$Bulan = '08';
					}
					else if($Time_Preq[1] == 'Sep'){
						$Bulan = '09';
					}
					else if($Time_Preq[1] == 'Oct'){
						$Bulan = '10';
					}
					else if($Time_Preq[1] == 'Nov'){
						$Bulan = '11';
					}
					else if($Time_Preq[1] == 'Dec'){
						$Bulan = '12';
					}
					$PReqDate	= $Time_Preq[2].'-'.$Bulan.'-'.$Time_Preq[0];
					//end convert preq

					//requre date convert
					$Require_date = explode(" ",$sheetData[$j]['J']);
					if($Require_date[1] == 'Jan'){
						$Bulan_req = '01';
					}
					else if($Require_date[1] == 'Feb'){
						$Bulan_req = '02';
					}
					else if($Require_date[1] == 'Mar'){
						$Bulan_req = '03';
					}
					else if($Require_date[1] == 'Apr'){
						$Bulan_req = '04';
					}
					else if($Require_date[1] == 'Mei'){
						$Bulan_req = '05';
					}
					else if($Require_date[1] == 'Jun'){
						$Bulan_req = '06';
					}
					else if($Require_date[1] == 'Jul'){
						$Bulan_req = '07';
					}
					else if($Require_date[1] == 'Aug'){
						$Bulan_req = '08';
					}
					else if($Require_date[1] == 'Sep'){
						$Bulan_req = '09';
					}
					else if($Require_date[1] == 'Oct'){
						$Bulan_req = '10';
					}
					else if($Require_date[1] == 'Nov'){
						$Bulan_req = '11';
					}
					else if($Require_date[1] == 'Dec'){
						$Bulan_req = '12';
					}
					$Req_Date = $Require_date[2].'-'.$Bulan_req.'-'.$Require_date[0];
					//end requre date convert
					$PReqNumber_New = $this->m_purchase_requisition->create_pr_number(date('d-m-Y'));
					
					if($OldPReqNumber_1 != $OldPReqNumber){
						$data = array(
							'BranchCode' 		=> $sheetData[$j]['N'],
							'DepartmentCode' 	=> $get_department->DepartmentCode,
							'PReqDate' 			=> $PReqDate,
							'PReqNumber' 		=> $PReqNumber_New,
							'PReqDesc' 			=> $sheetData[$j]['I'],
							//'BranchShipAddress' => 'NA',
							'AppLevel1Status' 	=> 1,
							'AppLevel1Code' 	=> $this->session->userdata('username'),
							'AppLevel1Date' 	=> date('Y-m-d'),
							'TransStatus' 		=> 1,
							'ImportStatus' 		=> 1,
							'OldPReqNumber' 	=> $sheetData[$j]['A'],
							'CreatedBy' 		=> $this->session->userdata('username'),
							'CreatedAt' 		=> date('Y-m-d'),
							'LastUser' 			=> $this->session->userdata('username')
						);
					
						$data_detail = array(
							'PReqNumber' 	=> $PReqNumber_New,
							'ItemCode' 		=> $item_master_code,
							'ItemDesc' 		=> $item_master_desc,
							'ItemUnit' 		=> $item_master_unit,
							'ItemQty' 		=> $sheetData[$j]['E'],
							'ItemQtyPO' 	=> $sheetData[$j]['G'],
							'ItemQtyRI' 	=> $sheetData[$j]['H'],
							'RequiredDate' 	=> $Req_Date,
							
							'ItemCategoryID' 	=> $item_master_category_id,
							'ItemCategoryCode' 	=> $item_master_category_name,
							'ItemType' 			=> $ItemType,
							'ItemStatus' 		=> $ItemStatus,
							'ItemPPh22Status' 	=> 0,
							'ItemPPh23Status' 	=> 0,
							'LastUser' 		=> $this->session->userdata('username')
						);
						
						$data_hisimport_detail = array(
							'BranchCode' 		=> $sheetData[$j]['N'],
							'ImportTransID' 	=> $num,
							'SourceNumber' 		=> $PReqNumber_New,
							'TransType' 		=> "PR", 
							'SourceDate' 		=> $sourceDate,
							'ImportNumber' 		=> $number_data,
							'LastUser' 			=> $this->session->userdata('username')
						);	
						
						$insert_result = $this->m_import_transaction->insert_purchase_requisition($data);
						//if($insert_result == false) {$this->trans_rollback('insert');}
						
						$insert_result = $this->m_import_transaction->insert_purchase_requisition_detail($data_detail);
						//if($insert_result == false) {$this->trans_rollback('insert');}
						
						$insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
						//if($insert_result == false) {$this->trans_rollback('insert');}
					
					}
					else{
						$get_preq = $this->m_import_transaction->get_preq_num($branch_code, $OldPReqNumber);
						$data_detail = array(
							'PReqNumber' 	=> $get_preq->PReqNumber,
							'ItemCode' 		=> $item_master_code,
							'ItemDesc' 		=> $item_master_desc,
							'ItemUnit' 		=> $item_master_unit,
							'ItemQty' 		=> $sheetData[$j]['E'],
							'ItemQtyPO' 	=> $sheetData[$j]['G'],
							'ItemQtyRI' 	=> $sheetData[$j]['H'],
							'RequiredDate' 	=> $Req_Date,
							
							'ItemCategoryID' 	=> $item_master_category_id,
							'ItemCategoryCode' 	=> $item_master_category_name,
							'ItemType' 			=> $ItemType,
							'ItemStatus' 		=> $ItemStatus,
							'ItemPPh22Status' 	=> 0,
							'ItemPPh23Status' 	=> 0,
							'LastUser' 		=> $this->session->userdata('username')
						);
						
						$insert_result = $this->m_import_transaction->insert_purchase_requisition_detail($data_detail);
						//if($insert_result == false) {$this->trans_rollback('insert');}
					}
					$OldPReqNumber_1 = $OldPReqNumber;
				}
			}
		}
		if($insert_result === false){
			$this->db->trans_rollback();
			$result['status']   = false;
			$result['message']  = get_notification('insert', 0);
			//$result['message']  = noticesImport("success",[]);
		}else{
			$this->db->trans_commit();
			$result['status']   = true;
			$result['message']  = get_notification('insert', 1);
			//$result['message']  = noticesImport("failed",[]);
		}
		echo json_encode($result);
	}
	
	public function import_purchase_order(){
		ini_set("max_execution_time", 'time_limit');
		ini_set('memory_limit', '1024M'); //your memory limit as string
		include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
		$filename = $_FILES['uploadfile']['tmp_name'];
		$objPHPExcel = PHPExcel_IOFactory::load($filename);
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
		$sheetCount = $objPHPExcel->getSheetCount();
		for($i=0; $i<=$sheetCount; $i++) {		
			if($i == 0){
				$objPHPExcel->setActiveSheetIndex($i);
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
				
				for($h=2;$h<=$lastRow;$h++){
					$OldVendorCode 	= $sheetData[$h]['A'];
					$OldPurchaseNo 	= $sheetData[$h]['C'];
					$BranchCode 	= $sheetData[$h]['Y'];
					$CurrencyName 	= $sheetData[$h]['P'];
					$Term 			= $sheetData[$h]['M'];
					$Disc 			= $sheetData[$h]['T'];
					
					$ItemCode 	 	= $sheetData[$h]['F'];
					$get_item_code  = $this->m_import_transaction->get_item_code($ItemCode);
					
					$get_currency 	= $this->m_import_transaction->get_currency_code($CurrencyName);
					$get_city 		= $this->m_import_transaction->get_am_city($City_Trouper);
					$get_vendor 	= $this->m_import_transaction->get_vendor_code($BranchCode, $OldVendorCode);
					
					$get_term 		= $this->m_import_transaction->get_term_code($Term);
					
					if(empty($OldVendorCode)){
						$result['message']  = 'Import Gagal Vendor No Tidak Boleh Kosong';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($CurrencyName)){
						$result['message']  = 'Import Gagal Currency Tidak Boleh Kosong';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_term)){
						$result['message']  = 'Import Gagal PO No '.$OldPurchaseNo.', Term '.$get_term.' Tidak Sama Dengan Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_item_code->ItemCode)){
						$result['message']  = 'Import Gagal Item Code '.$ItemCode.' Tidak Ada Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_vendor->OldVendorCode)){
						$result['message']  = 'Import Gagal Vendor Code '.$OldVendorCode.' Tidak Ada Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
				}
				
				$OldPONo_1 = '';
				$PreqNumb_1 = '';
				for($j=2;$j<=$lastRow;$j++){
					$OldVendorCode 	= $sheetData[$j]['A'];
					$BranchCode 	= $sheetData[$j]['Y'];
					$Term 			= $sheetData[$j]['M'];
					$OldPONo		= $sheetData[$j]['C'];
					$PreqNumb		= $sheetData[$j]['W'];
					$UnitPrice		= $sheetData[$j]['J'];
					$UnitPrice_Replace 	= str_replace(',', '', $UnitPrice);
					
					$Disc 			= $sheetData[$h]['T'];
					$Disc_Replace 	= str_replace(',', '', $Disc);
					
					$Qty			= $sheetData[$j]['H'];
					$Qty_Replace 	= str_replace(',', '', $Qty);
					
					$ItemCode 	 	= $sheetData[$j]['F'];
					$SubTotal 		= $sheetData[$j]['L'];
					$SubTotal_Replace 	= str_replace(',', '', $SubTotal);
					
					$CurrencyName 	= $sheetData[$j]['P'];
					$get_currency 	= $this->m_import_transaction->get_currency_code($CurrencyName);
					
					$get_vendor 	= $this->m_import_transaction->get_vendor_code($BranchCode, $OldVendorCode);
					
					$get_term 		= $this->m_import_transaction->get_term_code($Term);
					
					$get_item_code  = $this->m_import_transaction->get_item_code($ItemCode);
					
					//po date
					$PODate = explode(" ",$sheetData[$j]['D']);
					if($PODate[1] == 'Jan'){
						$Bulan_req = '01';
					}
					else if($PODate[1] == 'Feb'){
						$Bulan_req = '02';
					}
					else if($PODate[1] == 'Mar'){
						$Bulan_req = '03';
					}
					else if($PODate[1] == 'Apr'){
						$Bulan_req = '04';
					}
					else if($PODate[1] == 'Mei'){
						$Bulan_req = '05';
					}
					else if($PODate[1] == 'Jun'){
						$Bulan_req = '06';
					}
					else if($PODate[1] == 'Jul'){
						$Bulan_req = '07';
					}
					else if($PODate[1] == 'Aug'){
						$Bulan_req = '08';
					}
					else if($PODate[1] == 'Sep'){
						$Bulan_req = '09';
					}
					else if($PODate[1] == 'Oct'){
						$Bulan_req = '10';
					}
					else if($PODate[1] == 'Nov'){
						$Bulan_req = '11';
					}
					else if($PODate[1] == 'Dec'){
						$Bulan_req = '12';
					}
					$PODate = $PODate[2].'-'.$Bulan_req.'-'.$PODate[0];
					//end po date
					
					//expected date
					$ExpectedDate = explode(" ",$sheetData[$j]['N']);
					if($ExpectedDate[1] == 'Jan'){
						$Bulan_ex = '01';
					}
					else if($ExpectedDate[1] == 'Feb'){
						$Bulan_ex = '02';
					}
					else if($ExpectedDate[1] == 'Mar'){
						$Bulan_ex = '03';
					}
					else if($ExpectedDate[1] == 'Apr'){
						$Bulan_ex = '04';
					}
					else if($ExpectedDate[1] == 'Mei'){
						$Bulan_ex = '05';
					}
					else if($ExpectedDate[1] == 'Jun'){
						$Bulan_ex = '06';
					}
					else if($ExpectedDate[1] == 'Jul'){
						$Bulan_ex = '07';
					}
					else if($ExpectedDate[1] == 'Aug'){
						$Bulan_ex = '08';
					}
					else if($ExpectedDate[1] == 'Sep'){
						$Bulan_ex = '09';
					}
					else if($ExpectedDate[1] == 'Oct'){
						$Bulan_ex = '10';
					}
					else if($ExpectedDate[1] == 'Nov'){
						$Bulan_ex = '11';
					}
					else if($ExpectedDate[1] == 'Dec'){
						$Bulan_ex = '12';
					}
					$Expec_date = $ExpectedDate[2].'-'.$Bulan_ex.'-'.$ExpectedDate[0];
					//end
					
					$create_no_po = $this->m_purchase_order->create_po_number(date('d-m-Y'));
					$get_no_preq = $this->m_import_transaction->get_preq_detail($BranchCode, $sheetData[$j]['W']);
					
					if(!empty($get_no_preq->PReqNumber)){
						$get_preq = $this->m_import_transaction->get_preq_num($BranchCode, $PreqNumb);
						$data_detail = array(
							'PReqNumber' 	=> $get_preq->PReqNumber,
							'ItemCode' 		=> $get_item_code->ItemCode,
							'ItemDesc' 		=> $get_item_code->ItemDesc,
							'ItemUnit' 		=> $get_item_code->ItemUnit,
							'ItemQty' 		=> $Qty_Replace,
							'ItemQtyPO' 	=> $Qty_Replace,
							'ItemQtyRI' 	=> 0,
							'RequiredDate' 	=> $PODate,
							'PReqDesc' 		=> 'Purchase Requisition Dummy',
							'LastUser' 		=> $this->session->userdata('username')
						);
						
						$insert_result = $this->m_import_transaction->insert_purchase_requisition_detail($data_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
							
						$Preq = $get_no_preq->PReqNumber;
						$PReqdate 		= $get_no_preq->PReqDate;
						$PReqDetailID 	= $get_no_preq->PReqDetailID;
					}
					else{
						$Preq = $this->m_purchases_requisition->create_preq_number();
						$PReqdate = $PODate;
						if($PreqNumb_1 != $PreqNumb){
							$data = array(
								'BranchCode' 		=> $BranchCode,
								'DepartmentCode' 	=> $this->session->userdata('company').'-'.'HO'.'-'.'JKT'.'-'.'009',
								'PReqDate' 			=> $PODate,
								'PReqNumber' 		=> $Preq,
								'PReqDesc' 			=> 'Purchase Requisition Dummy',
								'BranchShipAddress' => 'NA',
								'AppLevel1Status' 	=> 1,
								'AppLevel1Code' 	=> $this->session->userdata('username'),
								'AppLevel1Date' 	=> date('Y-m-d'),
								'TransStatus' 		=> 1,
								'ImportStatus' 		=> 1,
								'OldPReqNumber' 	=> $PreqNumb,
								'LastUser' 			=> $this->session->userdata('username')
							);
						
							$data_detail = array(
								'PReqNumber' 	=> $Preq,
								'ItemCode' 		=> $get_item_code->ItemCode,
								'ItemDesc' 		=> $get_item_code->ItemDesc,
								'ItemUnit' 		=> $get_item_code->ItemUnit,
								'ItemQty' 		=> $Qty_Replace,
								'ItemQtyPO' 	=> $Qty_Replace,
								'ItemQtyRI' 	=> 0,
								'RequiredDate' 	=> $PODate,
								'PReqDesc' 		=> 'Purchase Requisition Dummy',
								'LastUser' 		=> $this->session->userdata('username')
							);
							
							$insert_result = $this->m_import_transaction->insert_purchase_requisition($data);
							if($insert_result == 0) {$this->trans_rollback('insert');}
							
							$insert_result = $this->m_import_transaction->insert_purchase_requisition_detail($data_detail);
							if($insert_result == 0) {$this->trans_rollback('insert');}
						}
						$PreqNumb_1 = $PreqNumb;
						
						//$get_no_preq_det = $this->m_import_transaction->get_preq_detail($BranchCode, $Preq);
						$PReqDetailID 	= $this->m_import_transaction->insert_purchase_requisition_detail($data_detail);
					}
					
					if($sheetData[$j]['K'] == "T"){
						$Pajak = 1;
						$ppn_kode = 'PPN';
						
						$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
						$tax = $get_ppn_taxes->TaxesRate;
						$ppn = ($Qty_Replace * $UnitPrice_Replace) * ($get_ppn_taxes->TaxesRate / 100);
						$ppn_replace = str_replace(',', '', $ppn);
					}
					else if($sheetData[$j]['K'] == "TE"){
						$ppn_kode = 'PPH22';
						$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
						$tax = $get_ppn_taxes->TaxesRate;
						$ppn = ($Qty_Replace * $UnitPrice_Replace) * ($get_ppn_taxes->TaxesRate / 100);
						$ppn_replace = str_replace(',', '', $ppn);
					}
					else{
						$ppn = 0;
					}
					
					$Sub_Total = ($Qty_Replace * $UnitPrice_Replace);
					//$total_amount = ($Qty_Replace * $UnitPrice_Replace) - $Disc_Replace + $ppn_replace;
					
					if($OldPONo_1 != $OldPONo){
						$data = array(
							'BranchCode' 		=> $BranchCode,
							'VendorCode' 		=> $get_vendor->VendorCode,
							'POrdDate' 			=> $PODate,
							'POrdNumber' 		=> $create_no_po,
							'PReqDate' 			=> $PReqdate,
							'PReqNumber' 		=> $Preq,
							'ExpectedDate' 		=> $Expec_date,
							'ShipmentID' 		=> 1,
							'TermPaymentID' 	=> $get_term,
							'FOBID' 			=> 1,
							'BillingAddress' 	=> $get_vendor->VendorAddress,
							'ShippingAddress' 	=> $get_vendor->VendorAddress,
							'POrdDesc' 			=> $sheetData[$j]['E'],
							'POrdDiscount' 		=> $Disc_Replace,
							'POrdPPn10Pcnt' 	=> $tax,
							'POrdPPn10' 		=> $ppn_replace,
							'POrdEstFreight' 	=> str_replace(',', '', $sheetData[$j]['U']),
							'CurrencyCode' 		=> $get_currency->CurrencyCode,
							'CurrencyRate' 		=> str_replace(',', '', $sheetData[$j]['R']),
							'POrdTaxesStatus' 	=> $Pajak,
							'POrdTotalAmount' 	=> $SubTotal_Replace,
							'POrdSubTotal' 		=> $Sub_Total,
							'AppLevel1Status' 	=> 1,
							'AppLevel1Code' 	=> $this->session->userdata('username'),
							'AppLevel1Date' 	=> date('Y-m-d'),
							'AppLevel2Status' 	=> 1,
							'AppLevel2Code' 	=> $this->session->userdata('username'),
							'AppLevel2Date' 	=> date('Y-m-d'),
							'TransStatus' 		=> 6,
							'ImportStatus' 		=> 1,
							'OldPOrdNumber' 	=> $sheetData[$j]['C'],
							'LastUser' 			=> $this->session->userdata('username')
						);
						
						$insert_result = $this->m_import_transaction->insert_purchase_order($data);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$date_detail = array(
							'PReqDetailID' 		=> $PReqDetailID,
							'PReqNumber' 		=> $Preq,
							'POrdNumber' 		=> $create_no_po,
							'ItemCode' 			=> $get_item_code->ItemCode,
							'ItemDesc' 			=> $get_item_code->ItemDesc,
							'ItemQty' 			=> $Qty_Replace,
							'ItemUnit' 			=> $get_item_code->ItemUnit,
							'ItemPrice' 		=> $UnitPrice_Replace,
							'ItemAmount' 		=> $Sub_Total,
							'ItemCategoryID' 	=> $get_item_code->ItemCategoryID,
							'LastUser' 			=> $this->session->userdata('username')
						);
						$insert_result = $this->m_import_transaction->insert_po_detail($date_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
					}
					else{
						$get_pord_no = $this->m_import_transaction->get_po_num($BranchCode, $sheetData[$j]['C']);
						
						$date_detail = array(
							'PReqDetailID' 		=> $PReqDetailID,
							'PReqNumber' 		=> $get_pord_no->PReqNumber,
							'POrdNumber' 		=> $get_pord_no->POrdNumber,
							'ItemCode' 			=> $get_item_code->ItemCode,
							'ItemDesc' 			=> $get_item_code->ItemDesc,
							'ItemQty' 			=> $Qty_Replace,
							'ItemUnit' 			=> $get_item_code->ItemUnit,
							'ItemPrice' 		=> $UnitPrice_Replace,
							'ItemAmount' 		=> $Sub_Total,
							'ItemCategoryID' 	=> $get_item_code->ItemCategoryID,
							'LastUser' 			=> $this->session->userdata('username')
						);
						$insert_result = $this->m_import_transaction->insert_po_detail($date_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
					
						$loop_subtotal = $Sub_Total + $get_pord_no->POrdSubTotal;
						
						if($sheetData[$j]['K'] == "T"){
							$Pajak = 1;
							$ppn_kode = 'PPN';
							
							$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
							$tax = $get_ppn_taxes->TaxesRate;
							$ppn = $loop_subtotal * $get_ppn_taxes->TaxesRate / 100;
							$ppn_replace = str_replace(',', '', $ppn);
						}
						else if($sheetData[$j]['K'] == "TE"){
							$ppn_kode = 'PPH22';
							$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
							$tax = $get_ppn_taxes->TaxesRate;
							$ppn = $loop_subtotal * $get_ppn_taxes->TaxesRate / 100;
							$ppn_replace = str_replace(',', '', $ppn);
						}
						else{
							$ppn_replace = 0;
						}
						
						$upate_purchase = array(
							'POrdSubTotal' 	 => $loop_subtotal,
							'POrdPPn10' 	 => $ppn_replace,
						);
						
						$insert_result = $this->m_import_transaction->update_pord($upate_purchase, $sheetData[$j]['C']);
						if($insert_result == 0) {$this->trans_rollback('insert');}
					}
					$OldPONo_1 = $OldPONo;	
				}
			}
		}
		if ($insert_result === 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
            $result['message'] = get_notification_transaksi('Import', 'insert', 0);			
		}
		else {
			$this->db->trans_commit();
			 $result['status']   = true;
             $result['message'] = get_notification_transaksi('Import', 'insert', 1);			
		}
		echo json_encode($result);
	}
	
    public function import_asset(){
        try{
//            $rstBulan = rangeMonths("2013-03-22", "2016-03-02");
//            if(!empty($rstBulan)){throw new Exception("bulan=".$rstBulan);}
            
//            $testAr = [];
//            $testAr['a1']=34;
//            $testAr['a2']=798;
//            $testAr['a3']=808;
//            $testB['a3']=80800000;
//            $a3 = "a3";
//            foreach ($testAr as $key => $value){
//                if(isset($testB[$key])){
//                    throw new Exception("a3 ketemu diloop, = ".$testB[$key]);
//                }
//            }
//            if(in_array($a3, $testAr)){
//                throw new Exception("a3 ketemu, = ".$testAr[$a3]);
//            }else{
//                throw new Exception("a3 ga ketemu, = ".$testAr[$a3]);
//            }
//            $testa = array(
//                "MESIN GERGAJI",
//                "MESIN GERGAJI",
//                "MESIN GERGAJI"
//            );
//            $a3 = "MESIN GERGAJI";
//            if(in_array($a3, $testa)){
//                throw new Exception("a3 ketemu, = ".$testAr[$a3]);
//            }else{
//                throw new Exception("a3 ga ketemu, = ".$testAr[$a3]);
//            }
            
            
            
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];
            if($filename!=""&&$filename!=null){
                $objPHPExcel = PHPExcel_IOFactory::load($filename);
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount = $objPHPExcel->getSheetCount();
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
                $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
                if(notCaseSensitifNotSpace($sheetData[1]['A'])==notCaseSensitifNotSpace("Asset Code") &&  //pengecekkan header huruf tidak case sensitif dan spasi tidak dipermasalahkan, jd saat pengecekkan menghilangkan spasi serta huruf dipaksa sama jenisnya(Upper/lower),yg dipakai sekarang upper. ini function diambil dari helper customstring_helper.php
                    notCaseSensitifNotSpace($sheetData[1]['B'])==notCaseSensitifNotSpace("Asset Type Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['C'])==notCaseSensitifNotSpace("Purchase Date") &&
                    notCaseSensitifNotSpace($sheetData[1]['D'])==notCaseSensitifNotSpace("Usage Date") &&
                    notCaseSensitifNotSpace($sheetData[1]['E'])==notCaseSensitifNotSpace("Asset Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['F'])==notCaseSensitifNotSpace("Quantity") &&
                    notCaseSensitifNotSpace($sheetData[1]['G'])==notCaseSensitifNotSpace("Dept. Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['H'])==notCaseSensitifNotSpace("Last Journal Date") &&
                    notCaseSensitifNotSpace($sheetData[1]['I'])==notCaseSensitifNotSpace("Estimated Life") &&
                    notCaseSensitifNotSpace($sheetData[1]['J'])==notCaseSensitifNotSpace("Depreciation Method") &&
                    notCaseSensitifNotSpace($sheetData[1]['K'])==notCaseSensitifNotSpace("% Depr Rate") &&
                    notCaseSensitifNotSpace($sheetData[1]['L'])==notCaseSensitifNotSpace("Asset Account Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['M'])==notCaseSensitifNotSpace("Accum Deprec Acc Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['N'])==notCaseSensitifNotSpace("Deprec Exp Acc Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['O'])==notCaseSensitifNotSpace("Intangible") &&
                    notCaseSensitifNotSpace($sheetData[1]['P'])==notCaseSensitifNotSpace("Is Fiscal") &&
                    notCaseSensitifNotSpace($sheetData[1]['Q'])==notCaseSensitifNotSpace("Asset Cost") &&
                    notCaseSensitifNotSpace($sheetData[1]['R'])==notCaseSensitifNotSpace("Notes") &&
                    notCaseSensitifNotSpace($sheetData[1]['S'])==notCaseSensitifNotSpace("Branch")
                ){             
                    $dataImport = [];
                    $dataImport['data_hisimport']           = [];
                    $dataImport['data_hisimport_detail']    = [];
                    $dataImport['data_invendetail']         = [];
                    $dataImport['data_inventori_insert']    = [];
                    $dataImport['data_inventori_update']    = [];
                    $dataImport['journal_debet']            = [];
                    $dataImport['journal_credit']           = [];
                    $dataImport['journal_opening_balance']  = [];
                    $tempArrayCode                      = [];
                    $tempArrayName                      = [];
                    $tempArrayData                      = [];
                    $tempArrayInventoriesUpdated        = [];
                    $lastRowNoCode                      = 0;
					$CategoryPenyusutan = array();
					$StatusDep = false;
					$txt_jv_no = "";

                    $sourceDate     = date('Y-m-d');
                    $TransType      = 'Asset';
                    $DataType       = 'Insert';
                    $status         = 1;		
                    $num            = $this->m_import_transaction->num_importtrans();
                    $number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
                    $data_hisimport = array(
                        'ImportTransID' => $num,
                        'TransType' 	=> $TransType, 
                        'DataType'      => $DataType, 
                        'ImportStatus' 	=> $status,
                        'LastEdited' 	=> date('Y-m-d'),
                        'LastUser'      => $this->session->userdata('username')
                    );
                    $dataImport['data_hisimport'][] = $data_hisimport;
                    
					$jv_number = $this->m_journalvoucher->create_jv_number(date("Y-m-d"));
									
					$jv_group = array(
						'BranchCode' 		=> $this->session->userdata('branch'),
						'JVchDate' 			=> date("Y-m-d"),
						'JVchNumber' 		=> $jv_number,
						'JVchDesc' 			=> "Import Fixed Asset",
						'JVchType' 			=> 0,
						'AppLevel1Status' 	=> 1,
						'AppLevel1Code' 	=> $this->session->userdata('username'),
						'AppLevel1Date' 	=> date("Y-m-d"),
						'AppLevel2Status' 	=> 1,
						'AppLevel2Code' 	=> $this->session->userdata('username'),
						'AppLevel2Date' 	=> date("Y-m-d"),
						'TransStatus' 		=> 2,
						'AppFinished' 		=> 1,
						'JVchTotalDebet' 	=> 0,
						'JVchTotalCredit' 	=> 0,
						'CreatedBy' 		=> $this->session->userdata('username'),
						'CreatedAt' 		=> date("YmdHis"),
						'LastUser' 			=> $this->session->userdata('username')
					);
					$dataImport['jv_group'][] = $jv_group;
					
					$data_app_finish = array(
						'AppFinished' => 1,
						'JVchNumber' => $jv_number
					);
					$dataImport['update_app_finish'][] = $data_app_finish;
									                    
                    for($i=2;$i<=$lastRow;$i++){
                        $AssetCode          = upperNotSpace($sheetData[$i]['A']); 
                        $AssetTypeName      = $sheetData[$i]['B'];
                        $colPurchaseDate    = $sheetData[$i]['C'];
                        $colUsageDate       = $sheetData[$i]['D'];
                        $AssetName          = $sheetData[$i]['E'];
                        $colQuantity        = $sheetData[$i]['F'];
                        $deptName           = $sheetData[$i]['G'];
                        $EstimeLife         = $sheetData[$i]['I'];
                        $Depreciation       = $sheetData[$i]['J'];
                        $AccumDeprecAccName = $sheetData[$i]['M'];
                        $DeprecExpAccName   = $sheetData[$i]['N'];
                        $colAssetCost       = $sheetData[$i]['Q'];
                        $colNotes           = $sheetData[$i]['R'];
                        $Branch             = upperNotSpace($sheetData[$i]['S']);
                        $DateImport        = $sheetData[$i]['V'];
						$AkumAmount        = $sheetData[$i]['T'];
						 
                        $asset_type     = strtoupper($AssetTypeName);
                        $asset_name     = strtoupper($AssetName);

                        $get_asset_type = $this->m_import_transaction->get_fixaset_type($asset_type);
                        $get_item_name  = $this->m_import_transaction->get_item_by_name($asset_name);
                        $id_kategori 	= $get_item_name->ItemCategoryID;
                        $get_branch  	= $this->m_import_transaction->get_branch_by_company($Branch);
                        $company 	= $get_branch->CompanyCode;
                        $check_itemcode_in_inventories  = $this->m_import_transaction->check_num_item_in_inventories($Branch, $get_item_name->ItemCode);
                        
                        if((notCaseSensitifNotSpace($AssetCode)==null || notCaseSensitifNotSpace($AssetCode)=="") &&
                            (notCaseSensitifNotSpace($AssetTypeName)==null || notCaseSensitifNotSpace($AssetTypeName)=="")  &&
                            (notCaseSensitifNotSpace($colPurchaseDate)==null || notCaseSensitifNotSpace($colPurchaseDate)=="") &&
                            (notCaseSensitifNotSpace($colUsageDate)==null || notCaseSensitifNotSpace($colUsageDate)=="") &&
                            (notCaseSensitifNotSpace($AssetName)==null || notCaseSensitifNotSpace($AssetName)=="") &&
                            (notCaseSensitifNotSpace($colQuantity)==null || notCaseSensitifNotSpace($colQuantity)=="") &&
                            (notCaseSensitifNotSpace($deptName)==null || notCaseSensitifNotSpace($deptName)=="") &&
                            (notCaseSensitifNotSpace($EstimeLife)==null || notCaseSensitifNotSpace($EstimeLife)=="") &&
                            (notCaseSensitifNotSpace($Depreciation)==null || notCaseSensitifNotSpace($Depreciation)=="") &&
                            (notCaseSensitifNotSpace($Branch)==null || notCaseSensitifNotSpace($Branch)=="")
                        ){
                            
                        }
                        else if(notCaseSensitifNotSpace($AssetCode)==null || notCaseSensitifNotSpace($AssetCode)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Asset Code","line"=>$i]));
                        }
                        else if(in_array($AssetCode, $tempArrayCode)){
                            throw new Exception(noticesImport("duplicate", ["column"=>"Asset Code","code"=>$AssetCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(notCaseSensitifNotSpace($AssetTypeName)==null || notCaseSensitifNotSpace($AssetTypeName)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Asset Type Name","line"=>$i]));
                        }
                        else if(notCaseSensitifNotSpace($colPurchaseDate)==null || notCaseSensitifNotSpace($colPurchaseDate)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Purchase Date","line"=>$i]));
                        }
                        else if(notCaseSensitifNotSpace($colUsageDate)==null || notCaseSensitifNotSpace($colUsageDate)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Usage Date","line"=>$i]));
                        }
                        else if(notCaseSensitifNotSpace($AssetName)==null || notCaseSensitifNotSpace($AssetName)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Asset Name","line"=>$i]));
                        }
                        else if(notCaseSensitifNotSpace($colQuantity)==null || notCaseSensitifNotSpace($colQuantity)=="" ||notCaseSensitifNotSpace($colQuantity)*1 !=1){
                            throw new Exception(noticesImport("denied", ["column"=>"Quantity","line"=>$i]));
                        }
//                        else if(notCaseSensitifNotSpace($deptName)==null || notCaseSensitifNotSpace($deptName)==""){
//                            throw new Exception(noticesImport("denied", ["column"=>"Dept. Name","line"=>$i]));
//                        }
                        else if(notCaseSensitifNotSpace($EstimeLife)==null || notCaseSensitifNotSpace($EstimeLife)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Estimated Life","line"=>$i]));
                        }
                        else if(notCaseSensitifNotSpace($Depreciation)==null || notCaseSensitifNotSpace($Depreciation)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Depreciation Method","line"=>$i]));
                        }
                        else if(notCaseSensitifNotSpace($Branch)==null || notCaseSensitifNotSpace($Branch)==""){
                            throw new Exception(noticesImport("denied", ["column"=>"Branch Code","line"=>$i]));
                        }
                        else if(empty($get_branch->BranchCode)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Branch","code"=>$Branch,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(empty($get_asset_type->FixedAssetType)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Asset Type Name =".$get_asset_type->FixedAssetType."=","code"=>$asset_type,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(empty($get_item_name->ItemDesc)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Asset Name","code"=>$asset_name,"di"=>" Master Item","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else{
                            (notCaseSensitifNotSpace($deptName)==null || notCaseSensitifNotSpace($deptName)=="")?$deptName=null:$deptName=$deptName;
                            $category_name = explode(' ', $get_item_name->ItemCategoryName);

							if (count($category_name) > 1) {
								$name_1st = substr($category_name[0], 0, 1);
								$name_2nd = substr($category_name[1], 0, 1);
								$asset_name = $name_1st . $name_2nd;
							} else {
								$asset_name = substr($category_name[0], 0, 2);
							}
							
							$NewAssetCode               = $Branch."/". $asset_name.'-'.code4Digit($AssetCode);
                            $existAssetCodeInInvendetail= $this->m_import_transaction->check_num_assetcode_in_invendetail($NewAssetCode);
                            if($existAssetCodeInInvendetail){
                                throw new Exception(noticesImport("sameInTable", ["column"=>"Asset Code","code"=>$NewAssetCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                            }
                            $tempArrayCode[]        = $NewAssetCode;                   
                            
                            $asset_cost = str_replace(',','',$colAssetCost);
                            
//                            $exp_estimet_years      = explode('Yr',$EstimeLife);                        
//                            $Estimet_years          = str_replace(' ','',$exp_estimet_years[0])*1;
//                            $exp_estimet_month      = explode('Mth',$exp_estimet_years[1]);        
//                            $Estimet_month          = str_replace(' ','',$exp_estimet_month[0])*1;                            
//                            $total_month            = ($Estimet_years*12)+$Estimet_month;
							
							 if(in_array($AssetName, $tempArrayName)){ //jika di data excel tidak ada yg sama                                    
                                $itemQty_Lama       = $tempArrayData[$get_item_name->ItemCode]['ItemQty'];
                                $ItemValue_Lama     = $tempArrayData[$get_item_name->ItemCode]['ItemValue'];
                                $itemAverage_Lama   = $tempArrayData[$get_item_name->ItemCode]['ItemAverage'];
                                if(($tempArrayDataTempInsert[$get_item_name->ItemCode]["ItemQty"])>0){
                                    $itemQty_Lama       = $tempArrayDataTempInsert[$get_item_name->ItemCode]['ItemQty'] + $itemQty_Lama;
                                    $ItemValue_Lama     = (($itemQty_Lama*1)*($itemAverage_Lama*1))+ ($tempArrayDataTempInsert[$get_item_name->ItemCode]['ItemQty'] * $tempArrayDataTempInsert[$get_item_name->ItemCode]['ItemAverage']);
                                    $itemAverage_Lama   = (($ItemValue_Lama*1)+(($tempArrayDataTempInsert[$get_item_name->ItemCode]['ItemValue'])) ) / (($itemQty_Lama*1)+($tempArrayDataTempInsert[$get_item_name->ItemCode]['ItemQty']*1));
                                    
                                    $tempArrayDataTempInsert[$get_item_name->ItemCode]=array(                               
                                        'BranchCode'    => $Branch,
                                        'ItemCode'      => $get_item_name->ItemCode,
                                        "ItemQty"       => 0,
                                        "ItemValue"     => 0,
                                        "ItemAverage"   => 0,
                                        'LastUser'      => $this->session->userdata('username')
                                    );
                                }
                                
                                    
                                $tempArrayData[$get_item_name->ItemCode]=array(
                                    'BranchCode'    => $Branch,
                                    'ItemCode'      => $get_item_name->ItemCode,
                                    "ItemQty"       => ($itemQty_Lama *1)+($colQuantity*1),
                                    "ItemValue"     => (($colQuantity*1)*($asset_cost*1))+ (($itemQty_Lama*1)*($itemAverage_Lama*1)),
                                    "ItemAverage"   => (($ItemValue_Lama*1)+(($colQuantity*1)*($asset_cost*1)) ) / (($itemQty_Lama*1)+($colQuantity*1)),
                                    'LastUser'      => $this->session->userdata('username')
                                );
                                in_array($get_item_name->ItemCode, $tempArrayInventoriesUpdated)?"":$tempArrayInventoriesUpdated[]=$get_item_name->ItemCode;
                            }
                            else{//klo data di excel ada yang sama brarti diupdate  
                                $resultNumItem = $this->m_import_transaction->check_num_item_in_inventories($Branch,$get_item_name->ItemCode);//hasil function true(ada)/false(ga ada)
                                if($resultNumItem){ //true brarti ada di table inventories
                                    if(empty($tempArrayData[$get_item_name->ItemCode])){//klo data temporery array blm ada, maka akan dibuat
                                        $get_inventories    = $this->m_import_transaction->get_inventories($Branch,$get_item_name->ItemCode);                                        
                                        $itemQty_Lama       = $get_inventories->ItemQty;
                                        $ItemValue_Lama     = $get_inventories->ItemValue;
                                        $itemAverage_Lama   = $get_inventories->ItemAverage;
                                        
                                        $tempArrayData[$get_item_name->ItemCode]=array(                               
                                            'BranchCode'    => $Branch,
                                            'ItemCode'      => $get_item_name->ItemCode,
                                            "ItemQty"       => ($itemQty_Lama *1)+($colQuantity*1),
                                            "ItemValue"     => (($colQuantity*1)*($asset_cost*1))+ (($itemQty_Lama*1)*($itemAverage_Lama*1)),
                                            "ItemAverage"   => (($ItemValue_Lama*1)+(($colQuantity*1)*($asset_cost*1)) ) / (($itemQty_Lama*1)+($colQuantity*1)),
                                            'LastUser'      => $this->session->userdata('username')
                                        );
                                        in_array($get_item_name->ItemCode, $tempArrayInventoriesUpdated)?"":$tempArrayInventoriesUpdated[]=$get_item_name->ItemCode;
                                    }else{
                                        $itemQty_Lama       = $tempArrayData[$get_item_name->ItemCode]['ItemQty'];
                                        $ItemValue_Lama     = $tempArrayData[$get_item_name->ItemCode]['ItemValue'];
                                        $itemAverage_Lama   = $tempArrayData[$get_item_name->ItemCode]['ItemAverage'];
                                        $tempArrayData[$get_item_name->ItemCode]=array(                                            
                                            'BranchCode'    => $Branch,
                                            'ItemCode'      => $get_item_name->ItemCode,
                                            "ItemQty"       => ($itemQty_Lama *1)+($colQuantity*1),
                                            "ItemValue"     => (($colQuantity*1)*($asset_cost*1))+ (($itemQty_Lama*1)*($itemAverage_Lama*1)),
                                            "ItemAverage"   => (($ItemValue_Lama*1)+(($colQuantity*1)*($asset_cost*1)) ) / (($itemQty_Lama*1)+($colQuantity*1)),
                                            'LastUser'      => $this->session->userdata('username')
                                        );
                                        in_array($get_item_name->ItemCode, $tempArrayInventoriesUpdated)?"":$tempArrayInventoriesUpdated[]=$get_item_name->ItemCode;
                                    }
                                }else{//klo tidak ditemukan di tabel inventories brarti di insert
                                    $statusHistoryDetail    = 1;
                                    $total_value_inventori  = $asset_cost * $colQuantity;
                                    $data_inventori_insert  = array(
                                        'BranchCode' 	=> $Branch,
                                        'ItemCode' 	=> $get_item_name->ItemCode,
                                        'ItemQty' 	=> $colQuantity,
                                        'ItemValue' 	=> $total_value_inventori,
                                        'ItemAverage' 	=> $asset_cost,
                                        'LastUser' 	=> $this->session->userdata('username')
                                    );
                                    $dataImport['data_inventori_insert'][] = $data_inventori_insert;
                                    
                                    $tempArrayDataTempInsert[$get_item_name->ItemCode]=array(                               
                                        'BranchCode'    => $Branch,
                                        'ItemCode'      => $get_item_name->ItemCode,
                                        "ItemQty"       => $colQuantity,
                                        "ItemValue"     => $total_value_inventori,
                                        "ItemAverage"   => $asset_cost,
                                        'LastUser'      => $this->session->userdata('username')
                                    );
                                }
                            }                            
                            $tempArrayName[]        = $AssetName;
							
                            $total_month            = $get_asset_type->EstimatedLife;
                                                        
                            $purchase_date  = explode(" ",$colPurchaseDate);
                            $Bulan_ex       = dateMMMtoMM($purchase_date[1]);
                            $PurchaseDate   = $purchase_date[2].'-'.$Bulan_ex.'-'.$purchase_date[0];
                            
                            $usage_date     = explode(" ",$colUsageDate);
                            $mont_usage     = dateMMMtoMM($usage_date[1]);
                            $UsageDate      = $usage_date[2].'-'.$mont_usage.'-'.$usage_date[0];
                                                        
                            $statusHistoryDetail = 0;
                            
							$statusHistoryDetail = 1;
							$strtotimeLife  = strtotime("+".$total_month." months", strtotime($PurchaseDate));
							$EstimeLifeDate = date('Y-m',$strtotimeLife);
							if($EstimeLifeDate >= date('Y-m') ){
								$rstRangeMonth      = rangeMonths($PurchaseDate,$DateImport);//hasil function sudah otomatis dikurangi 1
								if($AkumAmount != 0){
									$nominalPenyusutan  = doubleval($asset_cost * ($rstRangeMonth) / $total_month);
								}
								else{
									$nominalPenyusutan  = 0;
								}
								//echo "Tes";
							}else{
								//echo "Tes 1";
								$rstRangeMonth      = $total_month;
								if($AkumAmount != 0){
									$nominalPenyusutan  = doubleval(($colQuantity ) * ($asset_cost));
								}
								else{
									$nominalPenyusutan  = 0;
								}
							}
							
							$data_invendetail = array(
								'BranchCode' 	=> $Branch,
								'ReceiptNumber' 	=> $Branch."/".$num,//belum ketemu /belum pasti
								'ReceiptDate'       => $PurchaseDate,
								'UsageDate' 	=> $UsageDate,
								'ItemCode'          => $get_item_name->ItemCode,
								'ItemDesc'          => $get_item_name->ItemDesc,
								'ItemQty'           => ($colQuantity *1),
								'ItemAverage' 	=> "{$asset_cost}",
								//'PaymentAmount' 	=> "{$nominalPenyusutan}",//payment amount sudah tidak dipakai /*12-05-2016*/
								'PaymentPeriod' 	=> $rstRangeMonth,
								'AmountBookValues' 	=> 0,
								'ItemCategoryID' 	=> $get_item_name->ItemCategoryID,
								'DepartmentCode' 	=> $deptName,
								'Description' 	=> $colNotes,
								'AssetCode' 	=> $NewAssetCode,
								'SoldStatus' 	=> 0,
								'LastUser'          => $this->session->userdata('username')
							);
							$dataImport['data_invendetail'][]  = $data_invendetail;                                
							
							if($Depreciation=="Straight Line Method"){//cek Straight Line Method
								@$CategoryPenyusutan[$get_item_name->ItemCategoryID] += $nominalPenyusutan;
								@$SumPenyusutan += $nominalPenyusutan;	
								/*
									JV Group
								*/
								//if(($asset_cost) - ($nominalPenyusutan) > 0){
									
									$data_group_jv = array(
										//'JVchTotalDebet' 	=> $nominalPenyusutan,
										//'JVchTotalCredit' 	=> $nominalPenyusutan,
										'BranchCode' => $Branch,
										'JVchNumber' => $jv_number
									);
									$dataImport['update_jv_group'][] = $data_group_jv;
									
									$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
									if($OpeningBalance == false) {
										throw new Exception('Journal Opening Balance belum tersedia di COA silahkan lihat kembali COA');
									}
					
									$get_fixasset_type = $this->m_fixed_asset_type->get_fix_asset_type_journal($get_item_name->ItemCategoryID);
									if($get_fixasset_type == false) {throw new Exception('Account Fix Asset Type Belum terbuat silahkan cek kembali File anda');} 
									
									$jv_detail_debet = array(
										'JVchNumber' 		=> $jv_number,
										'JVchAccount' 		=> $OpeningBalance->AccountNumber,
										'JVchDebetSaldo' 	=> $nominalPenyusutan,
										'JVchCreditSaldo' 	=> 0,
										'JVchDetailMemo' 	=> "Import Fixed Asset",
										'JVchDetailDept' 	=> " ",
										'JVchRate' 			=> 1,
										'CurrencyCode' 		=> 'IDR',
										'AssetCode' 		=> $NewAssetCode,
										'LastUser' 			=> $this->session->userdata('username')
									);
									$dataImport['jv_detail'][] = $jv_detail_debet;
									
									$jv_detail_credit = array(
										'JVchNumber' 		=> $jv_number,
										'JVchAccount' 		=> $get_fixasset_type->AccumAccountNumber,
										'JVchDebetSaldo' 	=> 0,
										'JVchCreditSaldo' 	=> $nominalPenyusutan,
										'JVchDetailMemo' 	=> "Import Fixed Asset",
										'JVchDetailDept' 	=> " ",
										'JVchRate' 			=> 1,
										'CurrencyCode' 		=> 'IDR',
										'AssetCode' 		=> $NewAssetCode,
										'LastUser' 			=> $this->session->userdata('username')
									);
									$dataImport['jv_detail'][] = $jv_detail_credit;
									
									$jv_journal_debet = array(
										'JVchDate' 			=> date('Y-m-d'),
										'JVchNumber' 		=> $jv_number,
										'JVchDesc' 			=> 'Import Fixed Asset',
										'JVchAccountNumber' => $OpeningBalance->AccountNumber,
										'JVchSaldoDebet' 	=> $nominalPenyusutan,
										'JVchSaldoCredit' 	=> 0,
										'JVchSignStatus' 	=> 1,
										'AmountCurrency' 	=> $nominalPenyusutan,
										'LastUser' 			=> $this->session->userdata('username')
									);
									
									$dataImport['journal_debet_jv'][] = $jv_journal_debet;
									
									$jv_journal_credit = array(
										'JVchDate' 			=> date('Y-m-d'),
										'JVchNumber' 		=> $jv_number,
										'JVchDesc' 			=> 'Import Fixed Asset',
										'JVchAccountNumber' => $get_fixasset_type->AccumAccountNumber,
										'JVchSaldoDebet' 	=> 0,
										'JVchSaldoCredit' 	=> $nominalPenyusutan,
										'JVchSignStatus' 	=> 0,
										'AmountCurrency' 	=> $nominalPenyusutan,
										'LastUser' 			=> $this->session->userdata('username')
									);
									
									$dataImport['journal_credit_jv'][] = $jv_journal_credit;
								//}
								/*=================================================ENd====================================================*/
							
                            }//end cek Straight Line Method
                            
//                            $hasil = $this->m_import_transaction->check_num_item_in_inventories($Branch,$get_item_name->ItemCode);
//                            if($hasil){
//                                throw new Exception("hasil true , branch , itemcode = $Branch ; ".$get_item_name->ItemCode);
//                            }else{
//                                throw new Exception("hasil false , branch , itemcode = $Branch ; ".$get_item_name->ItemCode);
//                            }
                            
                            if($statusHistoryDetail == 1){
                                $data_hisimport_detail = array(
                                    'BranchCode'        => $Branch,
                                    'ImportTransID'     => $num,
                                    'SourceNumber'      => $NewAssetCode,
                                    'TransType'         => $TransType, 
                                    'SourceDate'        => $sourceDate,
                                    'ImportNumber'      => $number_data,
                                    'LastUser'          => $this->session->userdata('username')
                                );	
                                $dataImport['data_hisimport_detail'][] = $data_hisimport_detail;
                            }
                            
                            @$CategoryAmount[$get_item_name->ItemCategoryID] += $asset_cost;
							@$SumCostAsset += $asset_cost;
							@$BranchCode = $Branch;
							
                            $CatBranchComp[$get_item_name->ItemCategoryID] ['Branch'] = $Branch;
                            $CatBranchComp[$get_item_name->ItemCategoryID] ['company'] = $company;
                            $CatBranchComp[$get_item_name->ItemCategoryID] ['Debet'] = $this->m_import_transaction->get_accountnumber_by_accountname($company,$Branch,$AccumDeprecAccName);
                            $CatBranchComp[$get_item_name->ItemCategoryID] ['Credit'] = $this->m_import_transaction->get_accountnumber_by_accountname($company,$Branch,$DeprecExpAccName);
						}
                    }
                    //throw new Exception(json_encode($CategoryPenyusutan));
                    foreach($tempArrayInventoriesUpdated as $key){//pembuatan array untuk data update
                        $data_inventori_update = array(
                            'BranchCode' 	=> $tempArrayData[$key]["BranchCode"],
                            'ItemCode' 		=> $tempArrayData[$key]["ItemCode"],
                            'ItemQty' 		=> $tempArrayData[$key]["ItemQty"],
                            'ItemValue' 	=> $tempArrayData[$key]["ItemValue"],
                            'ItemAverage' 	=> $tempArrayData[$key]["ItemAverage"],
                            'LastUser' 		=> $tempArrayData[$key]["LastUser"]
                        );
                        $dataImport['data_inventori_update'][] = $data_inventori_update;                                
                    }
					
					 
					$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
					if($OpeningBalance == false) {
						throw new Exception('Journal Opening Balance belum tersedia di COA silahkan lihat kembali COA');
					}
					
                    foreach ($CategoryAmount as $key => $value) {
						$InventoryAccount   = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');
						if($InventoryAccount == false) {throw new Exception(noticesImport("jurnalNotComplete", []));} 
						
						$Branch 				= $CatBranchComp[$key]['Branch'];
						$create_number_asset  	= $this->m_import_transaction->create_asset_number($Branch);
						
						$journal_debet = array(
							'BranchCode'            => $Branch,
							'ItfAssetNumber'        => $create_number_asset,
							'ItemCategoryID'        => $key,
							'ImportTransID'        	=> $num,
							'ItfAssetDate'          => date("Y-m-d"),
							'ItfAssetAccountNumber' => $InventoryAccount->AccountNumber,
							'ItfAssetSaldoDebet'    => $value,
							'ItfAssetSaldoCredit'   => 0,
							'AmountCurrency'        => $value,
							'ItfAssetSignStatus'    => 0,
							'LastUser'              => $this->session->userdata('username')
						);
						$dataImport['journal_debet'][] = $journal_debet;
						
						$journal_credit = array(
							'BranchCode'            => $Branch,
							'ItfAssetNumber'        => $create_number_asset,
							'ItemCategoryID'        => $key,
							'ImportTransID'        	=> $num,
							'ItfAssetDate'          => date("Y-m-d"),
							'ItfAssetAccountNumber' => $OpeningBalance->AccountNumber,
							'ItfAssetSaldoDebet'    => 0,
							'ItfAssetSaldoCredit'   => $value,
							'AmountCurrency'        => $value,
							'ItfAssetSignStatus'    => 0,
							'LastUser'              => $this->session->userdata('username')
						);
						$dataImport['journal_credit'][] = $journal_credit;
					}
					
					/*===================================End============================*/
					
					
//                    $result['tempArrayName'] = $tempArrayName;
                    //$result['dataImport'] = $dataImport;
                    //throw new Exception("ngelu John");
                             
                   $rstImport = $this->m_import_transaction->importAsset($dataImport);
                   if($rstImport){
                        $result['status']   = true;
                        $result['message']  = get_notification('insert', 0);
                    }else{
                        $result['status']   = false;
                        $result['message']  = get_notification('insert', 1);
                    }  
                    echo json_encode($result);
                }
                else if(notCaseSensitifNotSpace($sheetData[1]['A']) != notCaseSensitifNotSpace("Asset Code")){
                    throw new Exception(noticesImport("notCell",["column"=>"Asset Code","code"=>"A1"]));
                }
                else if($sheetData[1]['B'] != 'Asset Type Name'){
                    throw new Exception(noticesImport("notCell",["column"=>"Asset Type Name","code"=>"B1"]));
                }
                else if($sheetData[1]['C'] != 'Purchase Date'){
                    throw new Exception(noticesImport("notCell",["column"=>"Purchase Date","code"=>"C1"]));
                }
                else if($sheetData[1]['D'] != 'Usage Date'){
                    throw new Exception(noticesImport("notCell",["column"=>"Usage Date","code"=>"D1"]));
                }
                else if($sheetData[1]['E'] != 'Asset Name'){
                    throw new Exception(noticesImport("notCell",["column"=>"Asset Name","code"=>"E1"]));
                }
                else if($sheetData[1]['F'] != 'Quantity'){
                    throw new Exception(noticesImport("notCell",["column"=>"Quantity","code"=>"F1"]));
                }
                else if($sheetData[1]['G'] != 'Dept. Name'){
                    throw new Exception(noticesImport("notCell",["column"=>"Dept. Name","code"=>"G1"]));
                }
                else if($sheetData[1]['H'] != 'Last Journal Date'){
                    throw new Exception(noticesImport("notCell",["column"=>"Last Journal Date","code"=>"H1"]));
                }
                else if($sheetData[1]['I'] != 'Estimated Life'){
                    throw new Exception(noticesImport("notCell",["column"=>"Estimated Life","code"=>"I1"]));
                }
                else if($sheetData[1]['J'] != 'Depreciation Method'){
                    throw new Exception(noticesImport("notCell",["column"=>"Depreciation Method","code"=>"J1"]));
                }
                else if($sheetData[1]['K'] != '% Depr Rate'){
                    throw new Exception(noticesImport("notCell",["column"=>"% Depr Rate","code"=>"K1"]));
                }
                else if($sheetData[1]['L'] != 'Asset Account Name'){
                    throw new Exception(noticesImport("notCell",["column"=>"Asset Account Name","code"=>"L1"]));
                }
                else if($sheetData[1]['M'] != 'Accum Deprec Acc Name'){
                    throw new Exception(noticesImport("notCell",["column"=>"Accum Deprec Acc Name","code"=>"M1"]));
                }
                else if($sheetData[1]['N'] != 'Deprec Exp Acc Name'){
                    throw new Exception(noticesImport("notCell",["column"=>"Deprec Exp Acc Name","code"=>"N1"]));
                }
                else if($sheetData[1]['O'] != 'Intangible'){
                    throw new Exception(noticesImport("notCell",["column"=>"Intangible","code"=>"O1"]));
                }
                else if($sheetData[1]['P'] != 'Is Fiscal'){
                    throw new Exception(noticesImport("notCell",["column"=>"Is Fiscal","code"=>"P1"]));
                }
                else if($sheetData[1]['Q'] != 'Asset Cost'){
                    throw new Exception(noticesImport("notCell",["column"=>"Asset Cost","code"=>"Q1"]));
                }
                else if($sheetData[1]['R'] != 'Notes'){
                    throw new Exception(noticesImport("notCell",["column"=>"Notes","code"=>"R1"]));
                }
                else if($sheetData[1]['S'] != 'Branch'){
                    throw new Exception(noticesImport("notCell",["column"=>"Branch","code"=>"S1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }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);
        }
    }
        
	public function import_assetLAMA(){
		ini_set("max_execution_time", 'time_limit');
		ini_set('memory_limit', '1024M'); //your memory limit as string
		include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
		$filename = $_FILES['uploadfile']['tmp_name'];
		$objPHPExcel = PHPExcel_IOFactory::load($filename);
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
		$sheetCount = $objPHPExcel->getSheetCount();
		for($i=0; $i<=$sheetCount; $i++) {		
			if($i == 0){
				$objPHPExcel->setActiveSheetIndex($i);
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
				
				for($l=1; $l<=$lastRow; $l++){
					if($sheetData[1]['A'] != 'Asset Code'){
						$result['message']  = 'Cell A1 Ini Bukan Asset Code';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['B'] != 'Asset Type Name'){
						$result['message']  = 'Cell B1 Ini Bukan Asset Type Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['C'] != 'Purchase Date'){
						$result['message']  = 'Cell C1 Ini Purchase Date';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['D'] != 'Usage Date'){
						$result['message']  = 'Cell D1 Ini Bukan Usage Date';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['E'] != 'Asset Name'){
						$result['message']  = 'Cell E1 Ini Bukan Asset Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['F'] != 'Quantity'){
						$result['message']  = 'Cell F1 Ini Bukan Quantity';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['G'] != 'Dept. Name'){
						$result['message']  = 'Cell G1 Ini Bukan Dept. Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['H'] != 'Last Journal Date'){
						$result['message']  = 'Cell H1 Ini Bukan Last Journal Date';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['I'] != 'Estimated Life'){
						$result['message']  = 'Cell I1 Ini Bukan Estimated Life';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['J'] != 'Depreciation Method'){
						$result['message']  = 'Cell J1 Ini Bukan Depreciation Method';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['K'] != '% Depr Rate'){
						$result['message']  = 'Cell K1 Ini Bukan % Depr Rate';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['L'] != 'Asset Account Name'){
						$result['message']  = 'Cell L1 Ini Bukan Asset Account Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['M'] != 'Accum Deprec Acc Name'){
						$result['message']  = 'Cell M1 Ini Bukan Accum Deprec Acc Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['N'] != 'Deprec Exp Acc Name'){
						$result['message']  = 'Cell N1 Ini Bukan Deprec Exp Acc Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['O'] != 'Intangible'){
						$result['message']  = 'Cell O1 Ini Bukan Intangible';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['P'] != 'Is Fiscal'){
						$result['message']  = 'Cell P1 Ini Bukan Is Fiscal';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['Q'] != 'Asset Cost'){
						$result['message']  = 'Cell Q1 Ini Bukan Asset Cost';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['R'] != 'Notes'){
						$result['message']  = 'Cell R1 Ini Bukan Notes';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['S'] != 'Branch'){
						$result['message']  = 'Cell S1 Ini Bukan Branch';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					
				}
				
				for($h=2;$h<=$lastRow;$h++){
					$AssetCode 		= $sheetData[$h]['A'];
					$AssetTypeName 	= $sheetData[$h]['B'];
					
					$AssetName	 	= $sheetData[$h]['E'];
					
					$asset_type = strtoupper($AssetTypeName);
					$asset_name = strtoupper($AssetName);
					
					$get_asset_type = $this->m_import_transaction->get_fixaset_type($asset_type);
					$get_item_name  = $this->m_import_transaction->get_item_by_name($asset_name);
					
					if(empty($AssetCode)){
						$result['message']  = 'Import Gagal Asset Code Tidak Boleh Kosong';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_asset_type->FixedAssetType)){
						$result['message']  = 'Import Gagal Asset Type Name'.$asset_type.' Tidak Ada Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_item_name->ItemDesc)){
						$result['message']  = 'Import Gagal Asset Name'.$asset_name.' Tidak Ada Di Master Item';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
				}
				
				$sourceDate  		= date('Y-m-d');
				$TransType 			= 'Asset';
				$DataType 			= 'Insert';
				$status 			= 1;
		
				//$this->db->like('TransType', 'Fixed Asset');
           		$num    = $this->db->get('ah_importtrans')->num_rows() + 1;
				
				
				$this->db->like('TransType', 'Fixed Asset');
           		$number_data    = $this->db->get('ah_importtransdetail')->num_rows() + 1;
				
				$data_hisimport = array(
					'ImportTransID' => $num,
					'TransType' 	=> $TransType, 
					'DataType' 		=> $DataType, 
					'ImportStatus' 	=> $status,
					'LastEdited' 	=> date('Y-m-d'),
					'LastUser' 		=> $this->session->userdata('username')
				);
				
				$this->db->trans_begin();
				$insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
				if($insert_result == 0) {$this->trans_rollback('insert');}
				
				$name_asset_1 = '';
				for($j=2;$j<=$lastRow;$j++){
					$EstimeLife 		= $sheetData[$j]['I'];
					$code_asset 		= $sheetData[$j]['A'];
					$SourceNumber  		= $sheetData[$j]['A'];
					$Branch  			= $sheetData[$j]['S'];
					$total_estimate 	= 0;
					$total_rate 		= 0;
					$presentase			= 0;
					
					$Estimet_years = substr($EstimeLife,0,2);
					$Estimet_years_explode = explode(' ',$Estimet_years);
					
					$Estimet_month = substr($EstimeLife,5,3);
					//$Estimet_mont_explode = explode(' ',$Estimet_month);
					
					$asset_cost = str_replace(',','',$sheetData[$j]['Q']);
					
					
					//formula estimate rate
					$total_estimate = $Estimet_month + $Estimet_years_explode[0];
					
					if($total_estimate == 0){
						$search_mont = 0;
						$total_rate = 0;
						$presentase = 0;
					}
					else{
						$search_mont = $total_estimate * 12;
						$total_rate = $search_mont / 12;
						$presentase = 100 / $total_rate;
					}
					//end/////////////////////
					
					$purchase_date = explode(" ",$sheetData[$j]['C']);
					if($purchase_date[1] == 'Jan'){
						$Bulan_ex = '01';
					}
					else if($purchase_date[1] == 'Feb'){
						$Bulan_ex = '02';
					}
					else if($purchase_date[1] == 'Mar'){
						$Bulan_ex = '03';
					}
					else if($purchase_date[1] == 'Apr'){
						$Bulan_ex = '04';
					}
					else if($purchase_date[1] == 'Mei'){
						$Bulan_ex = '05';
					}
					else if($purchase_date[1] == 'Jun'){
						$Bulan_ex = '06';
					}
					else if($purchase_date[1] == 'Jul'){
						$Bulan_ex = '07';
					}
					else if($purchase_date[1] == 'Aug'){
						$Bulan_ex = '08';
					}
					else if($purchase_date[1] == 'Sep'){
						$Bulan_ex = '09';
					}
					else if($purchase_date[1] == 'Oct'){
						$Bulan_ex = '10';
					}
					else if($purchase_date[1] == 'Nov'){
						$Bulan_ex = '11';
					}
					else if($purchase_date[1] == 'Dec'){
						$Bulan_ex = '12';
					}
					$PurchaseDate = $purchase_date[2].'-'.$Bulan_ex.'-'.$purchase_date[0];
					//////////////////////////////////////////////////////////////////////
					
					
					/////////////////////////usage date///////////////////////////////
					$usage_date = explode(" ",$sheetData[$j]['D']);
					if($usage_date[1] == 'Jan'){
						$mont_usage = '01';
					}
					else if($usage_date[1] == 'Feb'){
						$mont_usage = '02';
					}
					else if($usage_date[1] == 'Mar'){
						$mont_usage = '03';
					}
					else if($usage_date[1] == 'Apr'){
						$mont_usage = '04';
					}
					else if($usage_date[1] == 'Mei'){
						$mont_usage = '05';
					}
					else if($usage_date[1] == 'Jun'){
						$mont_usage = '06';
					}
					else if($usage_date[1] == 'Jul'){
						$mont_usage = '07';
					}
					else if($usage_date[1] == 'Aug'){
						$mont_usage = '08';
					}
					else if($usage_date[1] == 'Sep'){
						$mont_usage = '09';
					}
					else if($usage_date[1] == 'Oct'){
						$mont_usage = '10';
					}
					else if($usage_date[1] == 'Nov'){
						$mont_usage = '11';
					}
					else if($usage_date[1] == 'Dec'){
						$mont_usage = '12';
					}
					$UsageDate = $usage_date[2].'-'.$mont_usage.'-'.$usage_date[0];
					
					$AssetName	 	= $sheetData[$j]['E'];
					$asset_name = strtoupper($AssetName);
					
					$sourceDate  		= date('Y-m-d');
					
					
					$get_item_name  = $this->m_import_transaction->get_item_by_name($asset_name);
					$id_kategori 	= $get_item_name->ItemCategoryID;
					$get_branch  	= $this->m_import_transaction->get_branch_by_company($sheetData[$j]['S']);
					$company 		= $get_branch->CompanyCode;
					if($name_asset_1 != $AssetName){
						$total_value_inventori = $asset_cost * $sheetData[$j]['F'];
						
						$data = array(
							'ItemCode' 		=> $get_item_name->ItemCode,
							'ItemQty' 		=> $sheetData[$j]['F'],
							'ItemCategoryID' => $get_item_name->ItemCategoryID,
							'ItemAverage' 	=> $asset_cost,
							'ItemDesc' 		=> $get_item_name->ItemDesc,
							'Description' 	=> $sheetData[$j]['R'],
							'UsageDate' 	=> $UsageDate,
							//'PurchaseDate' 	=> $PurchaseDate,
							'AssetCode' 	=> $sheetData[$j]['A'],
							'BranchCode' 	=> $sheetData[$j]['S'],
							'LastUser' 		=> $this->session->userdata('username')
						);
					
						$insert_result = $this->m_import_transaction->am_fixedassettype($data);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$data_inventori = array(
							'BranchCode' 	=> $sheetData[$j]['S'],
							'ItemCode' 		=> $get_item_name->ItemCode,
							'ItemQty' 		=> $sheetData[$j]['F'],
							'ItemValue' 	=> $total_value_inventori,
							'ItemAverage' 	=> $asset_cost,
							'LastUser' 		=> $this->session->userdata('username')
						);
						
						$insert_result = $this->m_import_transaction->insert_at_inventories($data_inventori);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$data_hisimport_detail = array(
							'BranchCode' 		=> $sheetData[$j]['S'],
							'ImportTransID' 	=> $num,
							'SourceNumber' 		=> $sheetData[$j]['A'],
							'TransType' 		=> $TransType, 
							'SourceDate' 		=> $sourceDate,
							'ImportNumber' 		=> $number_data,
							'LastUser' 			=> $this->session->userdata('username')
						);	
						
						$insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
					}
					else{
						$data = array(
							'ItemCode' 		=> $get_item_name->ItemCode,
							'ItemQty' 		=> $sheetData[$j]['F'],
							'ItemCategoryID' => $get_item_name->ItemCategoryID,
							'ItemAverage' 	=> $asset_cost,
							'ItemDesc' 		=> $get_item_name->ItemDesc,
							'Description' 	=> $sheetData[$j]['R'],
							'UsageDate' 	=> $UsageDate,
							//'PurchaseDate' 	=> $PurchaseDate,
							'AssetCode' 	=> $sheetData[$j]['A'],
							'BranchCode' 	=> $sheetData[$j]['S'],
							'LastUser' 		=> $this->session->userdata('username')
						);
					
						$insert_result = $this->m_import_transaction->am_fixedassettype($data);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$data_hisimport_detail = array(
							'BranchCode' 		=> $sheetData[$j]['S'],
							'ImportTransID' 	=> $num,
							'SourceNumber' 		=> $sheetData[$j]['A'],
							'TransType' 		=> $TransType, 
							'SourceDate' 		=> $sourceDate,
							'ImportNumber' 		=> $number_data,
							'LastUser' 			=> $this->session->userdata('username')
						);	
						
						$insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$get_item_by_code  = $this->m_import_transaction->cek_item_oninventories($get_item_name->ItemCode);
						$total_qty 				= $sheetData[$j]['F'] + $get_item_by_code->ItemQty;
						$total_val_inventori 	= $asset_cost * $total_qty;
						
						$data_inventori = array(
							'BranchCode' 	=> $sheetData[$j]['S'],
							'ItemCode' 		=> $get_item_name->ItemCode,
							'ItemQty' 		=> $total_qty,
							'ItemValue' 	=> $total_val_inventori,
							'ItemAverage' 	=> $asset_cost,
							'LastUser' 		=> $this->session->userdata('username')
						);
						$insert_result = $this->m_import_transaction->update_inventoris($data_inventori, $get_item_name->ItemCode);
						if($insert_result == 0) {$this->trans_rollback('insert');}
					}
					$name_asset_1 = $AssetName;	
					
					
					@$CategoryAmount[$get_item_name->ItemCategoryID] += $asset_cost;
				}
					foreach ($CategoryAmount as $key => $value) {
						$InventoryAccount   = $this->m_import_transaction->get_item_account('Inventory', $key, $Branch,$company);
						if($InventoryAccount == false){                    
							$result_edit = 0;
							$this->trans_rollback('journal');
						}
						else{
							$create_number_asset  = $this->m_import_transaction->create_asset_number($Branch);
							$journal_debet = array(
								'BranchCode' 				=> $sheetData[$j]['S'],
								'ItfAssetNumber' 			=> $create_number_asset,
								'ItemCategoryID' 			=> $key,
								'ItfAssetDate' 				=> date("Y-m-d"),
								'ItfAssetAccountNumber' 	=> $InventoryAccount->AccountNumber,
								'ItfAssetSaldoDebet' 		=> $value,
								'ItfAssetSaldoCredit' 		=> 0,
								'AmountCurrency'	 		=> $value,
								'ItfAssetSignStatus' 		=> 0,
								'LastUser' 					=> $this->session->userdata('username')
							);
							
							$insert_result = $this->m_import_transaction->insert_journal_at_itfassetjournal($journal_debet);
							if($insert_result == 0) {$this->trans_rollback('insert');}
							
							$update_app_finished = array(
								'AppFinished' => 1
							);
							
							$insert_result = $this->m_import_transaction->update_app_finished($update_app_finished, $create_number_asset);
							if($insert_result == 0) {$this->trans_rollback('insert');}
						}
					}
			}
		}
		
		if ($insert_result === 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = get_notification_transaksi('Import', 'insert', 0);			
		}
		else {
			$this->db->trans_commit();
			 $result['status']   = true;
			 $result['message'] = get_notification_transaksi('Import', 'insert', 1);			
		}
		echo json_encode($result);
	}
	
	function to_print_journal_inventori(){	
        $data['menu_link']  = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
	
        //$id                 = str_replace($data['menu_link'].'/to_print_journal_inventori/',"",$this->uri->uri_string());
//	echo "uri_string =<b>{$this->uri->uri_string(3)}</b> <br>";	
//	echo "branch =<b>{$this->uri->segment(4)}</b> <br>";		
//	echo "ImportTransID =<b>{$this->uri->segment(5)}</b> <br>";		
	//echo "ItemCategoryID =<b>{$this->uri->segment(6)}</b> <br>";	
        $branch = $this->uri->segment(4);
        $ImportTransID = $this->uri->segment(5);
        $ItemCategoryID = $this->uri->segment(6);
        $data['detail']     = $this->m_import_transaction->get_detail_journal_inventori($branch,$ImportTransID,$ItemCategoryID);
        $data['list']       = $this->m_import_transaction->get_journal_by_number_inventori($branch);
	//echo $this->db->last_query();
        
        $this->load->view('v_header');
        $this->load->view('exim_transaction/v_journal_inventori',$data);
        $this->load->view('v_footer');		
    }
	
	function to_print_journal(){	
        $data['menu_link']  = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
	
        //$id                 = str_replace($data['menu_link'].'/to_print_journal/',"",$this->uri->uri_string());
		
        $branch = $this->uri->segment(4);
        $ImportTransID = $this->uri->segment(5);
        $ItemCategoryID = $this->uri->segment(6);
        
        $data['detail']     = $this->m_import_transaction->get_detail_journal($branch,$ImportTransID,$ItemCategoryID);
		$data['list']       = $this->m_import_transaction->get_journal_by_number($branch);
        //echo $this->db->last_query();
        $this->load->view('v_header');
        $this->load->view('exim_transaction/v_journal_asset',$data);
        $this->load->view('v_footer');		
    }
	
    public function import_item_inventories(){
        try{
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];
            if($filename!=""&&$filename!=null){
                $objPHPExcel = PHPExcel_IOFactory::load($filename);
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
                $sheetCount = $objPHPExcel->getSheetCount();	                            
                $objPHPExcel->setActiveSheetIndex(0);
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
                if( notCaseSensitifNotSpace($sheetData[1]['A'])==notCaseSensitifNotSpace("Item No.") && //pengecekkan header huruf tidak case sensitif dan spasi tidak dipermasalahkan, jd saat pengecekkan menghilangkan spasi serta huruf dipaksa sama jenisnya(Upper/lower),yg dipakai sekarang upper. ini function diambil dari helper customstring_helper.php
                    notCaseSensitifNotSpace($sheetData[1]['C'])==notCaseSensitifNotSpace("Quantity") &&
                    notCaseSensitifNotSpace($sheetData[1]['E'])==notCaseSensitifNotSpace("Average Cost")  &&
                    notCaseSensitifNotSpace($sheetData[1]['G'])==notCaseSensitifNotSpace("Item Type")  &&
                    notCaseSensitifNotSpace($sheetData[1]['H'])==notCaseSensitifNotSpace("Item Category Name") &&
                    notCaseSensitifNotSpace($sheetData[1]['I'])==notCaseSensitifNotSpace("Branch")    
                ){
                    $dataImport = [];
                    $dataImport['data_hisimport']           = [];
                    $dataImport['data_hisimport_detail']    = [];
                    $dataImport['data_inventories']         = [];
                    $dataImport["journal_debet"]            = [];
                    $dataImport['journal_opening_balance']  = [];
                    $tempArrayCode                          = [];
                    $CategoryAmount                         = [];
                    $HaveLoopData                           = 0;

                    $sourceDate     = date('Y-m-d');
                    $TransType      = 'Inventories';
                    $DataType       = 'Insert';
                    $status         = 1;		
                    $num            = $this->m_import_transaction->num_importtrans();
                    $number_data    = $this->m_import_transaction->num_importtransdetail($TransType);				
                    $data_hisimport = array(
                        'ImportTransID' => $num,
                        'TransType' 	=> $TransType, 
                        'DataType'      => $DataType, 
                        'ImportStatus' 	=> $status,
                        'LastEdited' 	=> date('Y-m-d'),
                        'LastUser'      => $this->session->userdata('username')
                    );
                    $dataImport['data_hisimport'][] = $data_hisimport;                    

                    for($i=2; $i<=$lastRow; $i++){
                        $ItemCode               = upperNotSpace($sheetData[$i]['A']);
                        $ItemQty                = str_replace(',','',$sheetData[$i]['C']);
                        $average_cost           = str_replace(',','',$sheetData[$i]['E']);
                        $ItemType               = strtoupper($sheetData[$i]['G']);
                        $ItemCategoryID         = $sheetData[$i]['H'];
                        $BranchCode             = upperNotSpace($sheetData[$i]['I']);
                        $ItemCategoryID_Trouper = strtoupper($ItemCategoryID);
                        $Item_value             = $average_cost * $ItemQty;

                        $get_item_kategori      = $this->m_import_transaction->get_item_kategori($ItemCategoryID_Trouper);
                        //$get_item_on_inventoris = $this->m_import_transaction->cek_item_oninventories($ItemCode);//ga di pake karena pengecekan cm itemcode saja
                        $get_item_on_inventoris = $this->m_import_transaction->check_num_item_in_inventories($BranchCode,$ItemCode);
                        $get_item_on_am_item    = $this->m_import_transaction->get_item_code($ItemCode);

                        $get_item_by_master     = $this->m_import_transaction->get_item_code($ItemCode);
                        $get_branch             = $this->m_import_transaction->get_branch_by_company($BranchCode);
						
                        $company                = $get_branch->CompanyCode;
                        $branch                 = $get_branch->BranchCode;
                        
                        if((notCaseSensitifNotSpace($ItemCode)==null || notCaseSensitifNotSpace($ItemCode)=="") &&
                            (notCaseSensitifNotSpace($ItemQty)==null || notCaseSensitifNotSpace($ItemQty)=="") &&
                            (notCaseSensitifNotSpace($average_cost)==null || notCaseSensitifNotSpace($average_cost)=="") &&
                            (notCaseSensitifNotSpace($ItemType)==null || notCaseSensitifNotSpace($ItemType)=="") &&
                            (notCaseSensitifNotSpace($ItemCategoryID)==null || notCaseSensitifNotSpace($ItemCategoryID)=="") &&
                            (notCaseSensitifNotSpace($BranchCode)==null || notCaseSensitifNotSpace($BranchCode)=="")
                        ){
                            //kosong semua skip
                        }
                        else if((notCaseSensitifNotSpace($ItemCode)==null || notCaseSensitifNotSpace($ItemCode)=="")){
                            throw new Exception(noticesImport("denied", ["column"=>"Item Code","line"=>$i]));
                        }
                        else if((notCaseSensitifNotSpace($ItemType)==null || notCaseSensitifNotSpace($ItemType)=="")){
                            throw new Exception(noticesImport("denied", ["column"=>"Item Type","line"=>$i]));
                        }
                        else if((notCaseSensitifNotSpace($ItemCategoryID)==null || notCaseSensitifNotSpace($ItemCategoryID)=="")){
                            throw new Exception(noticesImport("denied", ["column"=>"Item Category Name","line"=>$i]));
                        }
                        else if((notCaseSensitifNotSpace($BranchCode)==null || notCaseSensitifNotSpace($BranchCode)=="")){
                            throw new Exception(noticesImport("denied", ["column"=>"Branch Code","line"=>$i]));
                        }                        
                        else if(in_array($ItemCode, $tempArrayCode)){
                            throw new Exception(noticesImport("duplicate", ["column"=>"Item No","code"=>$ItemCode,"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }                        
                        else{
                            $tempArrayCode[] = $ItemCode;
                            if($ItemType == "INVENTORY PART"){
                                $HaveLoopData = 1;
                                if($get_item_on_inventoris){
                                    $result['get_item_on_inventoris']=$get_item_on_inventoris;
                                    throw new Exception(noticesImport("sameInTable", ["column"=>"Item No","code"=>$ItemCode,"di"=>"Inventoris","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                                }
                                else if(empty($get_item_on_am_item->ItemCode)){
                                    throw new Exception(noticesImport("notfound", ["column"=>"Item No","code"=>$ItemCode,"di"=>"Master Data","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                                }
                                else if(empty($get_item_kategori->ItemCategoryName)){
                                    throw new Exception(noticesImport("notfound", ["column"=>"Item Kategori","code"=>$ItemCategoryID,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                                }
                                else if((notCaseSensitifNotSpace($branch)==null || notCaseSensitifNotSpace($branch)=="")){
                                    throw new Exception(noticesImport("notfound", ["column"=>"Branch","code"=>$BranchCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                                }else{
                                    $data_inventories = array(
                                        'BranchCode'    => $branch,
                                        'ItemCode'      => $get_item_by_master->ItemCode,
                                        'ItemQty'       => $ItemQty,
                                        'ItemAverage'   => $average_cost,
                                        'ItemValue'     => $Item_value,
                                        'LastUser'      => $this->session->userdata('username')
                                    );
    //                                $insert_result = $this->m_import_transaction->insert_at_inventories($data);
    //                                if($insert_result == 0) {$this->trans_rollback('insert');}
                                    $dataImport['data_inventories'][] = $data_inventories;

                                    $data_hisimport_detail = array(
                                        'BranchCode' 	=> $branch,
                                        'ImportTransID' => $num,
                                        'SourceNumber' 	=> $sheetData[$i]['A'],
                                        'TransType' 	=> $TransType, 
                                        'SourceDate' 	=> $sourceDate,
                                        'ImportNumber' 	=> $number_data,
                                        'LastUser' 	=> $this->session->userdata('username')
                                    );	
    //                                $insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
    //                                if($insert_result == 0) {$this->trans_rollback('insert');}
                                    $dataImport['data_hisimport_detail'][] = $data_hisimport_detail;

                                    @$CategoryAmount[$get_item_kategori->ItemCategoryID] += $Item_value;
									@$Company_Branch = $company;
									@$Branch_data = $branch;
                                }
                            }
                        }
                    }

                    if($HaveLoopData==1){
                        foreach ($CategoryAmount as $key => $value) {
							$InventoryAccount       = $this->m_import_transaction->get_item_account('Inventory', $key, $Branch_data,$Company_Branch);
							$OpeningBalanceAccount  = $this->m_import_transaction->get_accountnumber_by_accountname($Company_Branch,$Branch_data,"Opening Balance");
                            
                            if($InventoryAccount == false){   
                                $result['get_item_on_inventoris']=$get_item_on_inventoris;
                                throw new Exception(noticesImport("jurnalNotComplete", []));
                            }
                            else{
                                //di sini bikin function untuk cari nomor accountnumber "Opening Balance"
                                //#accountnumbercredit = cariaccountnumber("opening balance", Branchcode, Companycode)
                                //$create_number_inventori  = $this->m_import_transaction->create_inventori_number($branch);//<==dimasukkan ke model
                                $journal_debet = array(
                                    'BranchCode'            => $Branch_data,
                                    'ITItemNumber'          => "",//$create_number_inventori
                                    'ItemCategoryID'        => $key,                                    
                                    'ImportTransID'         => $num,
                                    'ITItemDate'            => date("Y-m-d"),
                                    'ITItemAccountNumber'   => $InventoryAccount->AccountNumber,
                                    'ITItemSaldoDebet'      => $value,
                                    'ITItemSaldoCredit'     => 0, //value saldo credit adalah $value
                                    'AmountCurrency'        => $value,
                                    'ITItemSignStatus'      => 0,
                                    'LastUser'              => $this->session->userdata('username')
                                );
    //                            $insert_result = $this->m_import_transaction->insert_journal_at_ititemjournal($journal_debet);
    //                            if($insert_result == 0) {$this->trans_rollback('insert');}
                                $dataImport["journal_debet"][]= $journal_debet;
                                
                                $journal_opening_balance = array(
                                    'BranchCode'            => $Branch_data,
                                    'ITItemNumber'          => "",//$create_number_inventori
                                    'ItemCategoryID'        => $key,                                    
                                    'ImportTransID'        => $num,
                                    'ITItemDate'            => date("Y-m-d"),
                                    'ITItemAccountNumber'   => $OpeningBalanceAccount->AccountNumber,
                                    'ITItemSaldoDebet'      => 0,
                                    'ITItemSaldoCredit'     => $value, //value saldo credit adalah $value
                                    'AmountCurrency'        => $value,
                                    'ITItemSignStatus'      => 0,
                                    'LastUser'              => $this->session->userdata('username')
                                );
                                $dataImport["journal_opening_balance"][]= $journal_opening_balance;

    //                            $update_app_finished = array(//<==dimasukkan ke model
    //                                    'AppFinished' => 1
    //                            );
    //                            $insert_result = $this->m_import_transaction->update_app_finished_inventori($update_app_finished, $create_number_inventori);//<==dimasukkan ke model
    //                            if($insert_result == 0) {$this->trans_rollback('insert');}
                            }
                        }     
                        
                        $rstImport = $this->m_import_transaction->importInventories($dataImport);
                        //$rstImport = true;
                        if($rstImport){
                            $result['status']   = true;
                            $result['message']  = get_notification('insert', 1);
                            //$result['message'] = get_notification_transaksi('Import', 'insert', 1);//pemanggilan ni function error
                            //$result['message']  = noticesImport("success",[]);
                        }else{
                            $result['status']   = false;
                            $result['message']  = get_notification('insert', 0);
                            //$result['message'] = get_notification_transaksi('Import', 'insert', 0);//pemanggilan ni function error
                            //$result['message']  = noticesImport("failed",[]);
                        }  
                    }else{
                        $result['status']   = false;
                        $result['message']  = noticesImport("notInventoryPart", []);
                        //$result['message'] = get_notification_transaksi('Import', 'insert', 0);   //pemanggilan ni function error                   
                    }
                                  
                    echo json_encode($result);
                                
                }else if( notCaseSensitifNotSpace($sheetData[1]['A'])!=notCaseSensitifNotSpace("Item No.")){ 
                    throw new Exception(noticesImport("notCell",["column"=>"Item No.","code"=>"A1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if( notCaseSensitifNotSpace($sheetData[1]['C'])!=notCaseSensitifNotSpace("Quantity")){ 
                    throw new Exception(noticesImport("notCell",["column"=>"Quantity","code"=>"C1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if( notCaseSensitifNotSpace($sheetData[1]['E'])!=notCaseSensitifNotSpace("Average Cost")){ 
                    throw new Exception(noticesImport("notCell",["column"=>"Average Cost","code"=>"E1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if( notCaseSensitifNotSpace($sheetData[1]['G'])!=notCaseSensitifNotSpace("Item Type")){ 
                    throw new Exception(noticesImport("notCell",["column"=>"Item Type","code"=>"G1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if( notCaseSensitifNotSpace($sheetData[1]['H'])!=notCaseSensitifNotSpace("Item Category Name")){ 
                    throw new Exception(noticesImport("notCell",["column"=>"Item Category Name","code"=>"H1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }else if( notCaseSensitifNotSpace($sheetData[1]['I'])!=notCaseSensitifNotSpace("Branch") ){ 
                    throw new Exception(noticesImport("notCell",["column"=>"Branch","code"=>"I1"]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }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);
        }
    }
    
    public function import_item_inventoriesLAMA(){
            ini_set("max_execution_time", 'time_limit');
            ini_set('memory_limit', '1024M'); //your memory limit as string
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            $filename = $_FILES['uploadfile']['tmp_name'];
            $objPHPExcel = PHPExcel_IOFactory::load($filename);
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
            $sheetCount = $objPHPExcel->getSheetCount();
            for($i=0; $i<=$sheetCount; $i++) {		
                    if($i == 0){
                            $objPHPExcel->setActiveSheetIndex($i);
                            $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                            $lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();

                            $ItemCode_1 = '';
                            for($h=2; $h<=$lastRow; $h++){
                                    $ItemCode 	     	= $sheetData[$h]['A'];
                                    $ItemCategoryID  	= $sheetData[$h]['H'];
                                    $ItemCategoryID_Trouper = strtoupper($ItemCategoryID);

                                    $get_item_kategori 		 = $this->m_import_transaction->get_item_kategori($ItemCategoryID_Trouper);
                                    $get_item_on_inventoris  = $this->m_import_transaction->cek_item_oninventories($ItemCode);
                                    $get_item_on_am_item  	 = $this->m_import_transaction->get_item_code($ItemCode);

                                    if($ItemCode_1 == $ItemCode){
                                            $result['message']  = 'Import Gagal Item Code '.$ItemCode.' Tidak Boleh Sama';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(!empty($get_item_on_inventoris->ItemCode)){
                                            $result['message']  = 'Import Gagal Item Code '.$ItemCode.' Sudah Ada Di Inventoris';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(empty($get_item_on_am_item->ItemCode)){
                                            $result['message']  = 'Import Gagal Item Code '.$ItemCode.' Tidak Ada Di Master';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(empty($get_item_kategori->ItemCategoryName)){
                                            $result['message']  = 'Import Gagal Item Kategori '.$ItemCategoryID.' Tidak Ada Di Sistem';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    else if(empty($ItemCategoryID)){
                                            $result['message']  = 'Import Gagal Item Kategori Tidak Boleh Kosong';
                                            $result['status']   = false;

                                            echo json_encode($result);
                                            die();
                                    }
                                    $ItemCode_1 = $ItemCode;
                            }

                            $sourceDate  		= date('Y-m-d');
                            $TransType 			= 'Inventories';
                            $DataType 			= 'Insert';
                            $status 			= 1;

                            //$this->db->like('TransType', 'Item Inventories');
                    $num    = $this->db->get('ah_importtrans')->num_rows() + 1;

                            $this->db->like('TransType', 'Item Inventories');
                    $number_data    = $this->db->get('ah_importtransdetail')->num_rows() + 1;

                            $data_hisimport = array(
                                    'ImportTransID' => $num,
                                    'TransType' 	=> $TransType, 
                                    'DataType' 		=> $DataType, 
                                    'ImportStatus' 	=> $status,
                                    'LastUser' 		=> $this->session->userdata('username')
                            );

                            $this->db->trans_begin();
                            $insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
                            if($insert_result == 0) {$this->trans_rollback('insert');}

                            for($j=2;$j<=$lastRow;$j++){
                                    $ItemType 	     = strtoupper($sheetData[$j]['G']);
                                    if($ItemType == "INVENTORY PART"){
                                            $average_cost 	 = str_replace(',','',$sheetData[$j]['E']);
                                            $ItemCode 	     = $sheetData[$j]['A'];
                                            $ItemQty 	     = str_replace(',','',$sheetData[$j]['C']);

                                            $Item_value 	= $average_cost * $ItemQty;
                                            $sourceDate  	= date('Y-m-d');

                                            $ItemCategoryID  	= $sheetData[$j]['H'];
                                            $ItemCategoryID_Trouper = strtoupper($ItemCategoryID);

                                            $get_item_kategori 	= $this->m_import_transaction->get_item_kategori($ItemCategoryID_Trouper);
                                            $get_item_by_master = $this->m_import_transaction->get_item_code($ItemCode);
                                            $get_branch  		= $this->m_import_transaction->get_branch_by_company($sheetData[$j]['I']);
                                            $company 			= $get_branch->CompanyCode;
                                            $branch 			= $get_branch->BranchCode;

                                            $data = array(
                                                    'BranchCode' 	=> $branch,
                                                    'ItemCode' 		=> $get_item_by_master->ItemCode,
                                                    'ItemQty' 	 	=> $ItemQty,
                                                    'ItemAverage' 	=> $average_cost,
                                                    'ItemValue' 	=> $Item_value,
                                                    'LastUser' 		=> $this->session->userdata('username')
                                            );

                                            $insert_result = $this->m_import_transaction->insert_at_inventories($data);
                                            if($insert_result == 0) {$this->trans_rollback('insert');}

                                            $data_hisimport_detail = array(
                                                    'BranchCode' 		=> $branch,
                                                    'ImportTransID' 	=> $num,
                                                    'SourceNumber' 		=> $sheetData[$j]['A'],
                                                    'TransType' 		=> $TransType, 
                                                    'SourceDate' 		=> $sourceDate,
                                                    'ImportNumber' 		=> $number_data,
                                                    'LastUser' 			=> $this->session->userdata('username')
                                            );	

                                            $insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
                                            if($insert_result == 0) {$this->trans_rollback('insert');}

                                            @$CategoryAmount[$get_item_kategori->ItemCategoryID] += $Item_value;
                                    }
                                    else{

                                    }
                            }

                            if($ItemType == "INVENTORY PART"){
                                    foreach ($CategoryAmount as $key => $value) {
                                            $InventoryAccount   = $this->m_import_transaction->get_item_account('Inventory', $key, $branch,$company);
                                            if($InventoryAccount == false){                    
                                                    $result_edit = 0;
                                                    $this->trans_rollback('journal');
                                            }
                                            else{
                                                    $create_number_inventori  = $this->m_import_transaction->create_inventori_number($branch);
                                                    $journal_debet = array(
                                                            'BranchCode' 			=> $branch,
                                                            'ITItemNumber' 			=> $create_number_inventori,
                                                            'ItemCategoryID' 		=> $key,
                                                            'ITItemDate' 			=> date("Y-m-d"),
                                                            'ITItemAccountNumber' 	=> $InventoryAccount->AccountNumber,
                                                            'ITItemSaldoDebet' 		=> $value,
                                                            'ITItemSaldoCredit' 	=> 0,
                                                            'AmountCurrency'	 	=> $value,
                                                            'ITItemSignStatus' 		=> 0,
                                                            'LastUser' 				=> $this->session->userdata('username')
                                                    );

                                                    $insert_result = $this->m_import_transaction->insert_journal_at_ititemjournal($journal_debet);
                                                    if($insert_result == 0) {$this->trans_rollback('insert');}

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

                                                    $insert_result = $this->m_import_transaction->update_app_finished_inventori($update_app_finished, $create_number_inventori);
                                                    if($insert_result == 0) {$this->trans_rollback('insert');}
                                            }
                                    }
                            }
                    }
            }
            if ($insert_result === 0) {
                    $this->db->trans_rollback();
                    $result['status'] = false;
        $result['message'] = get_notification_transaksi('Import', 'insert', 0);			
            }
            else {
                    $this->db->trans_commit();
                     $result['status']   = true;
         $result['message'] = get_notification_transaksi('Import', 'insert', 1);			
            }
            echo json_encode($result);
    }
	
	public function import_sales_order(){
		ini_set("max_execution_time", 'time_limit');
		ini_set('memory_limit', '1024M'); //your memory limit as string
		include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
		$filename = $_FILES['uploadfile']['tmp_name'];
		$objPHPExcel = PHPExcel_IOFactory::load($filename);
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');		
		$sheetCount = $objPHPExcel->getSheetCount();
		for($i=0; $i<=$sheetCount; $i++) {		
			if($i == 0){
				$objPHPExcel->setActiveSheetIndex($i);
				$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
				$lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
				
				for($l=1; $l<=$lastRow; $l++){
					if($sheetData[1]['A'] != 'Customer No.'){
						$result['message']  = 'Cell A1 Ini Bukan Customer No.';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['B'] != 'Customer Name'){
						$result['message']  = 'Cell B1 Ini Bukan Customer Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['C'] != 'SO No'){
						$result['message']  = 'Cell C1 Ini SO No';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['D'] != 'SO Date'){
						$result['message']  = 'Cell D1 Ini Bukan SO Date';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['E'] != 'Description'){
						$result['message']  = 'Cell E1 Ini Bukan Description';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['F'] != 'Item No.'){
						$result['message']  = 'Cell F1 Ini Bukan Item No.';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['G'] != 'Item Description'){
						$result['message']  = 'Cell G1 Ini Bukan Item Description';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['H'] != 'Quantity'){
						$result['message']  = 'Cell H1 Ini Bukan Quantity';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['I'] != 'Unit'){
						$result['message']  = 'Cell I1 Ini Bukan Unit';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['J'] != 'Unit Price'){
						$result['message']  = 'Cell J1 Ini Bukan Unit Price';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['K'] != 'Tax code'){
						$result['message']  = 'Cell K1 Ini Bukan Tax code';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['L'] != 'Qty. Order'){
						$result['message']  = 'Cell L1 Ini Bukan Qty. Order';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['M'] != 'Status'){
						$result['message']  = 'Cell M1 Ini Bukan Status';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['N'] != 'Customer Term Net Days'){
						$result['message']  = 'Cell N1 Ini Bukan Deprec Exp Acc Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['O'] != 'Salesman Name'){
						$result['message']  = 'Cell O1 Ini Bukan Salesman Name';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
					else if($sheetData[1]['P'] != 'Ship Via'){
						$result['message']  = 'Cell P1 Ini Bukan Ship Via';
						$result['status']   = false;
							
						echo json_encode($result);
						die();
					}
				}
				
				for($h=2;$h<=$lastRow;$h++){
					$OldCustomerCode 	= $sheetData[$h]['A'];
					$branch 			= $sheetData[$h]['Q'];
					$ItemCode 			= $sheetData[$h]['F'];
					$Term 				= $sheetData[$h]['N'];
					$SalesCode 			= $sheetData[$h]['O'];
					$SalesName 			= strtoupper($SalesCode);
					
					$get_customer_code_so = $this->m_import_transaction->get_customer_code($branch, $OldCustomerCode);
					$get_item_code = $this->m_import_transaction->cek_item_oninventories($ItemCode);
					$get_term 		= $this->m_import_transaction->get_term_code($Term);
					$sales_code 		  = $this->m_import_transaction->get_employee_code($branch, $SalesName);
					
					if(empty($get_customer_code_so->CustomerCode)){
						$result['message']  = 'Import Gagal Customer Code '.$OldCustomerCode.' Belum Terdaftar Di Sistem';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_item_code->ItemCode)){
						$result['message']  = 'Import Gagal Item Code '.$ItemCode.' Tidak Ada Di Sistem Inventori';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($OldCustomerCode)){
						$result['message']  = 'Import Gagal SO Number Tidak Boleh Kosong Di Excel';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($get_term)){
						$result['message']  = 'Import Gagal Term '.$Term.' Tidak Ada Di Sistem Silahkan Input Terlebih Dahulu Term';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
					else if(empty($sales_code->EmployeeCode)){
						$result['message']  = 'Import Gagal Employee '.$SalesCode.' Tidak Ada Di Sistem Silahkan Input Terlebih Dahulu';
						$result['status']   = false;
						
						echo json_encode($result);
						die();
					}
				}
				
				$sourceDate  		= date('Y-m-d');
				$TransType 			= 'SO';
				$DataType 			= 'Insert';
				$status 			= 1;
		
           		$num    = $this->db->get('ah_importtrans')->num_rows() + 1;
				
				
				$this->db->like('TransType', 'SO');
           		$number_data    = $this->db->get('ah_importtransdetail')->num_rows() + 1;
				
				$data_hisimport = array(
					'ImportNumber' => $num,
					'ImportDate' 	=> $sourceDate,
					'TransType' 	=> $TransType, 
					'DataType' 		=> $DataType, 
					'ImportStatus' 	=> $status,
					'LastUser' 		=> $this->session->userdata('username')
				);
				
				$insert_result = $this->m_import_transaction->insert_history_transaction($data_hisimport);
				if($insert_result == 0) {$this->trans_rollback('insert');}
				
				$So_number_1 = '';
				for($j=2;$j<=$lastRow;$j++){
					$BranchCode 		= $sheetData[$j]['Q'];
					$So_number 			= $sheetData[$j]['C'];
					$OldCustomerCode 	= $sheetData[$j]['A'];
					
					$SalesCode 			= $sheetData[$j]['O'];
					$SalesName 			= strtoupper($SalesCode);
					
					$ItemCode 			= $sheetData[$j]['F'];
					$Ship 				= $sheetData[$j]['P'];
					
					$get_customer_code_so = $this->m_import_transaction->get_customer_code($BranchCode, $OldCustomerCode);
					$sales_code 		  = $this->m_import_transaction->get_employee_code($BranchCode, $SalesName);
					
					$get_item_code = $this->m_import_transaction->cek_item_oninventories($ItemCode);
					
					$Qty			= $sheetData[$j]['H'];
					$Qty_Replace 	= str_replace(',', '', $Qty);
					
					$Qty_so			= $sheetData[$j]['L'];
					$Qty_Replace_so = str_replace(',', '', $Qty_so);
					
					$Unit_Price				= $sheetData[$j]['J'];
					$Unit_price_replace 	= str_replace(',', '', $Unit_Price);
					
					$so_date = explode(" ",$sheetData[$j]['D']);
					if($so_date[1] == 'Jan'){
						$Bulan_ex = '01';
					}
					else if($so_date[1] == 'Feb'){
						$Bulan_ex = '02';
					}
					else if($so_date[1] == 'Mar'){
						$Bulan_ex = '03';
					}
					else if($so_date[1] == 'Apr'){
						$Bulan_ex = '04';
					}
					else if($so_date[1] == 'Mei'){
						$Bulan_ex = '05';
					}
					else if($so_date[1] == 'Jun'){
						$Bulan_ex = '06';
					}
					else if($so_date[1] == 'Jul'){
						$Bulan_ex = '07';
					}
					else if($so_date[1] == 'Aug'){
						$Bulan_ex = '08';
					}
					else if($so_date[1] == 'Sep'){
						$Bulan_ex = '09';
					}
					else if($so_date[1] == 'Oct'){
						$Bulan_ex = '10';
					}
					else if($so_date[1] == 'Nov'){
						$Bulan_ex = '11';
					}
					else if($so_date[1] == 'Dec'){
						$Bulan_ex = '12';
					}
					$SalesDate = $so_date[2].'-'.$Bulan_ex.'-'.$so_date[0];
					
					$create_no_sq 	= $this->m_sales_quotation->create_preq_number(date('d-m-Y'));
					$create_no_so 	= $this->m_sales_order->create_sord_number(date('d-m-Y'));
					$Term 			= $sheetData[$j]['N'];
					$get_term 		= $this->m_import_transaction->get_term_code($Term);
					
					$item_amount 	= $Unit_price_replace * $Qty_Replace;
					
					if($sheetData[$j]['K'] == "T"){
						$taxes_status = 1;
						$taxin_status = 0;
						$Pajak = 10;
						$ppn_kode = 'PPN';
						
						$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
						$tax = $get_ppn_taxes->TaxesRate;
						$ppn = ($Qty_Replace * $Unit_price_replace) * ($get_ppn_taxes->TaxesRate / 100);
						$ppn_replace = str_replace(',', '', $ppn);
					}
					else if($sheetData[$j]['K'] == "TE"){
						$taxes_status = 1;
						$taxin_status = 1;
						$Pajak = 10;
						$ppn_kode = 'PPH22';
						$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
						$tax = $get_ppn_taxes->TaxesRate;
						$ppn = ($Qty_Replace * $UnitPrice_Replace / 1.1) * ($get_ppn_taxes->TaxesRate / 100);
						$ppn_replace = str_replace(',', '', $ppn);
					}
					else{
						$ppn = 0;
						$Pajak = 0;
						$taxes_status = 0;
						$taxin_status = 0;
					}
					
					if($Ship == "LOCCO"){
						$ship_id = 1;
					}
					else{
						$ship_id = 2;
					}
					if($So_number_1 != $So_number){
						$data_sq = array(
							'BranchCode' 		=> $BranchCode,
							'CustomerCode' 		=> $get_customer_code_so->CustomerCode,
							'SQuoDate' 			=> $SalesDate,
							'SQuoNumber' 		=> $create_no_sq,
							'CustPODate' 		=> $SalesDate,
							'SalesmanCode' 		=> $sales_code->EmployeeCode,
							'BillingAddress' 	=> $get_customer_code_so->CustomerAddress,
							'ShippingAddress' 	=> $get_customer_code_so->CustomerAddress,
							'SQuoDesc' 			=> $sheetData[$j]['E'],
							'TransStatus' 		=> 1,
							'OldSQuoNumber' 	=> $So_number,
							'LastUser' 			=> $this->session->userdata('username')
						);
						$insert_result = $this->m_import_transaction->insert_sq($data_sq);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$data_sq_detail = array(
							'SQuoNumber' 	=> $create_no_sq,
							'ItemCode' 		=> $get_item_code->ItemCode,
							'ItemUnit' 		=> $get_item_code->ItemUnit,
							'ItemQty' 		=> $Qty_Replace,
							'ItemQtySO' 	=> $Qty_Replace,
							'RequiredDate'  => $SalesDate,
							'LastUser' 		=> $this->session->userdata('username')
						);
						$Sq_detail_id = $this->m_import_transaction->insert_sq_detail($data_sq_detail);
						if($Sq_detail_id == 0) {$this->trans_rollback('insert');}
						
						//$Sq_detail_id 	= $this->m_import_transaction->insert_sq_detail($data_sq_detail);
						
						$data_sales_order = array(
							'BranchCode' 		=> $BranchCode,
							'CustomerCode' 		=> $get_customer_code_so->CustomerCode,
							'SOrdDate	' 		=> $SalesDate,
							'SOrdNumber' 		=> $create_no_so,
							'SQuoDate' 			=> $SalesDate,
							'SQuoNumber' 		=> $create_no_sq,
							'CurrencyCode' 		=> $get_customer_code_so->CurrencyCode,
							'CurrencyRate' 		=> $get_customer_code_so->CurrencyRate,
							'CustPODate' 		=> $SalesDate,
							'CustPONumber' 		=> '123/MIGRASI',
							'BillingAddress' 	=> $get_customer_code_so->CustomerAddress,
							'ShippingAddress' 	=> $get_customer_code_so->CustomerAddress,
							'ShipmentID' 	 	=> $ship_id,
							'TermsPaymentID' 	=> $get_term,
							'SOrdSubTotal' 		=> $item_amount,
							'SOrdTaxPcnt' 		=> $Pajak,
							'SOrdTaxesStatus' 	=> $taxes_status,
							'SOrdInTaxStatus' 	=> $taxin_status,
							'AppLevel1Status' 	=> 1,
							'AppLevel1Code' 	=> $this->session->userdata('username'),
							'AppLevel1Date' 	=> date('Y-m-d'),
							'TransStatus' 		=> 1,
							'OldSOrdNumber' 	=> $So_number,
							'LastUser' 			=> $this->session->userdata('username')
						);
						$insert_result = $this->m_import_transaction->insert_so($data_sales_order);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$data_sales_order_detail = array(
							'SQuoDetailID' => $Sq_detail_id,
							'SQuoNumber'  => $create_no_sq,
							'SOrdNumber'  => $create_no_so,
							'ItemCode' 	  => $get_item_code->ItemCode,
							'ItemQty' 	  => $Qty_Replace,
							'ItemUnit' 	  => $get_item_code->ItemUnit,
							'ItemPrice'   => $Unit_price_replace,
							'ItemAmount'  => $item_amount,
							'ItemQtyDO'   => $Qty_Replace_so,
							'ItemQtyDOApp' => $Qty_Replace_so,
							'LastUser' 	  => $this->session->userdata('username')
						);
						$insert_result = $this->m_import_transaction->insert_so_detail($data_sales_order_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$loop_subtotal = $item_amount;
						
						if($sheetData[$j]['K'] == "T"){
							$taxes_status = 1;
							$taxin_status = 0;
							$Pajak = 10;
							$ppn_kode = 'PPN';
							
							$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
							$tax = $get_ppn_taxes->TaxesRate;
							$ppn = $loop_subtotal * ($get_ppn_taxes->TaxesRate / 100);
							$ppn_replace = str_replace(',', '', $ppn);
						}
						else if($sheetData[$j]['K'] == "TE"){
							$taxes_status = 1;
							$taxin_status = 1;
							$ppn_kode = 'PPH22';
							$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
							$tax = $get_ppn_taxes->TaxesRate;
							$ppn = ($loop_subtotal / 1.1) * ($get_ppn_taxes->TaxesRate / 100);
							$ppn_replace = str_replace(',', '', $ppn);
						}
						else{
							$ppn = 0;
						}
						
						$TotalAmount = $loop_subtotal + $ppn;
						$upate_so = array(
							'SOrdSubTotal' 	 	=> $loop_subtotal,
							'SOrdTaxes' 	 	=> $ppn,
							'SOrdTotalAmount' 	=> $TotalAmount
						);
						
						$insert_result = $this->m_import_transaction->update_sord($upate_so, $sheetData[$j]['C']);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$data_hisimport_detail = array(
							'ImportNumber' 		=> $num,
							'SourceNumber' 		=> $create_no_so,
							'TransType' 		=> $TransType, 
							'SourceDate' 		=> $sourceDate,
							'ImportDataNumber' 	=> $number_data,
						);
						
						$insert_result = $this->m_import_transaction->insert_ah_importtrans_detail($data_hisimport_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
					}
					else{
						$get_sreq_no = $this->m_import_transaction->get_sreq_num($BranchCode, $So_number);
						$get_sord_no = $this->m_import_transaction->get_sord_num($BranchCode, $So_number);
						
						$data_sq_detail = array(
							'SQuoNumber' 	=> $get_sreq_no->SQuoNumber,
							'ItemCode' 		=> $get_item_code->ItemCode,
							'ItemUnit' 		=> $get_item_code->ItemUnit,
							'ItemQty' 		=> $Qty_Replace,
							'ItemQtySO' 	=> $Qty_Replace,
							'RequiredDate'  => $SalesDate,
							'LastUser' 		=> $this->session->userdata('username')
						);
						$Sq_detail_id = $this->m_import_transaction->insert_sq_detail($data_sq_detail);
						if($Sq_detail_id == 0) {$this->trans_rollback('insert');}
						
						
						$data_sales_order_detail = array(
							'SQuoDetailID' => $Sq_detail_id,
							'SQuoNumber'  => $get_sreq_no->SQuoNumber,
							'SOrdNumber'  => $get_sord_no->SOrdNumber,
							'ItemCode' 	  => $get_item_code->ItemCode,
							'ItemQty' 	  => $Qty_Replace,
							'ItemUnit' 	  => $get_item_code->ItemUnit,
							'ItemPrice'   => $Unit_price_replace,
							'ItemAmount'  => $item_amount,
							'ItemQtyDO'   => $Qty_Replace_so,
							'ItemQtyDOApp' => $Qty_Replace_so,
							'LastUser' 	  => $this->session->userdata('username')
						);
						
						$insert_result = $this->m_import_transaction->insert_so_detail($data_sales_order_detail);
						if($insert_result == 0) {$this->trans_rollback('insert');}
						
						$loop_subtotal = $item_amount + $get_sord_no->SOrdSubTotal;
						
						if($sheetData[$j]['K'] == "T"){
							$taxes_status = 1;
							$taxin_status = 0;
							$Pajak = 10;
							$ppn_kode = 'PPN';
							
							$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
							$tax = $get_ppn_taxes->TaxesRate;
							$ppn = $loop_subtotal * ($get_ppn_taxes->TaxesRate / 100);
							$ppn_replace = str_replace(',', '', $ppn);
						}
						else if($sheetData[$j]['K'] == "TE"){
							$taxes_status = 1;
							$taxin_status = 1;
							$ppn_kode = 'PPH22';
							$get_ppn_taxes = $this->m_import_transaction->taxes_code($ppn_kode);
							$tax = $get_ppn_taxes->TaxesRate;
							$ppn = ($loop_subtotal / 1.1) * ($get_ppn_taxes->TaxesRate / 100);
							$ppn_replace = str_replace(',', '', $ppn);
						}
						else{
							$ppn = 0;
						}
						
						$TotalAmount = $loop_subtotal + $ppn;
						$upate_so = array(
							'SOrdSubTotal' 	 	=> $loop_subtotal,
							'SOrdTaxes' 	 	=> $ppn,
							'SOrdTotalAmount' 	=> $TotalAmount
						);
						
						$insert_result = $this->m_import_transaction->update_sord($upate_so, $sheetData[$j]['C']);
						if($insert_result == 0) {$this->trans_rollback('insert');}
					}
					$So_number_1 = $So_number;
				}
			}
		}
		if ($insert_result === 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
            $result['message'] = get_notification_transaksi('Import', 'insert', 0);			
		}
		else {
			$this->db->trans_commit();
			 $result['status']   = true;
             $result['message'] = get_notification_transaksi('Import', 'insert', 1);			
		}
		echo json_encode($result);
	}
}
/* End of file import_price_list.php */
/* Location: ./application/modules_core/file/controllers/import_price_list.php */