<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
Author      : Herpan / 31/09/2014 / controller for import price list
Revisi      : Ferry
Author      : Dhidhik / 18-02-2016 / mengubah logic import data excel pada function import_price_data
*/

class Import_price_list extends CI_Controller {	
    // inisialisasi manual
    public $menu_id 	= 252;
    //public $menu_model 	= 'm_itemprice';
    public $menu_model  = array('m_itemprice', 'list/m_currency', 'setup/m_branchinfo','login/m_login');
    
    public function __construct() {
        parent::__construct();
		$this->load->model($this->menu_model);	
                                        
		$this->load->helper('message');
		$this->load->helper('custom_string');
		$this->load->helper('notices_import_file'); 
	
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
		if($is_login){

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

			$uri_func = $this->uri->segment(3);
			if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
				redirect(base_url() . 'login', 'refresh');
			}else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
				$result['status']   = 'session';
				$result['message']  = get_notification('session_destroy',0);
				echo json_encode($result);
				die();
			}
		}
    }	
	
    public function index() {	
		if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');
					// 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('import_pricelist/v_import_pricelist',$data);
					$this->load->view('v_footer');	
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }	
    }
	
    //Function Menampilkan Data Pada Data Grid View
    public function ajax(){
		$page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$item_desc      = $this->input->post('ItemDesc') ? $this->input->post('ItemDesc') : '';
        $branch_name  = $this->input->post('BranchName') ? $this->input->post('BranchName') : '';
		
		$this->db->join('am_branch','am_itemprice.BranchCode=am_branch.BranchCode','INNER');
        $this->db->join('am_item','am_itemprice.ItemCode=am_item.ItemCode','INNER');
        $this->db->join('am_itemcategory','am_itemcategory.ItemcategoryID=am_item.ItemcategoryID','INNER');
		
		$this->db->where('am_itemprice.BranchCode',$this->session->userdata('branch'));
		$this->db->like('am_item.ItemDesc',$item_desc);
		$this->db->like('am_branch.BranchName',$branch_name);
		$count_data = $this->db->count_all_results('am_itemprice'); //change
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
		
		$result = $this->m_itemprice->get_all(); //change

        for ($i = 0; $i <= ($rows - 1); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()

            $hasil[] = array(
                'ItemCode' 		=> $result[$i]->ItemCode,
                'ItemDesc' 		=> $result[$i]->ItemDesc,
                'ItemUnit' 		=> $result[$i]->ItemUnit,
                'BranchName' 	=> $result[$i]->BranchName,
                'CurrencyCode' 	=> $result[$i]->CurrencyCode,
                'ItemPrice' 	=> $result[$i]->ItemPrice
            );
        }

        if (empty($hasil)) {
            $emptyVar = array();
            echo json_encode($emptyVar);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
		
        //echo json_encode($this->m_itemprice->get_all());		
    }	
	

    // Function Import
    public function import_price_data(){
        try{
            $column = array ('A','B','C','D');
            // menggunakan class phpExcel
            include_once(APPPATH."libraries/PHPExcel/IOFactory.php");
            // membaca file excel yang diupload
            $filename = $_FILES['uploadfile']['tmp_name'];

            if($filename!=""&&$filename!=null){
                $objPHPExcel = PHPExcel_IOFactory::load($filename);
                $objPHPExcel->setActiveSheetIndex(0);
                $numColExcel = $objPHPExcel->setActiveSheetIndex(0)->getHighestColumn();//untuk mengetahui banyak row yang telah dipakai, misal datanya 4 tetapi baris paling bawah yang pernah dipakai adalah baris 45,maka hasilnya 45 walaupun datanya hanya terdapat 4baris
                $numRowExcel = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();//hasilnya adalah huruf yang paling kanan yg dipakai, tp uniknya yg pernah dicoba adalah ada 4kolom yg terisi yg dimulai dr A, tp hasilnya E, tp kolom 9 diisi hasilnya 'i',, aneh,,
                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
                $dataItemPrice['dataUpdate']= [];
                $dataItemPrice['dataInsert']= [];
                $data=[];
                if( (notCaseSensitifNotSpace($sheetData[2]['A'])==notCaseSensitifNotSpace("itemcode"))  &&  //checking header excel formatnya tidak case sensitif dan tidak bermasalah di spasi,dgn nama header cell-nya "Item Code"
                    (notCaseSensitifNotSpace($sheetData[2]['B'])==notCaseSensitifNotSpace("currency"))  &&  //checking header excel formatnya tidak case sensitif dan tidak bermasalah di spasi,dgn nama header cell-nya "Currency"
                    (notCaseSensitifNotSpace($sheetData[2]['C'])==notCaseSensitifNotSpace("itemprice")) &&  //checking header excel formatnya tidak case sensitif dan tidak bermasalah di spasi,dgn nama header cell-nya "Item Price"
                    (notCaseSensitifNotSpace($sheetData[2]['D'])==notCaseSensitifNotSpace("branchcode"))  
                ){//checking header excel formatnya tidak case sensitif dan tidak bermasalah di spasi,dgn nama header cell-nya "Branch Code"
                    for($i=3;$i<=count($sheetData);$i++){
                    //for($i=3;$i<$numRowExcel;$i++){
                        /*========================deklar variabel dari excel======================================*/
                        $ItemCode       = $sheetData[$i][$column[0]];
                        $Currency       = $sheetData[$i][$column[1]];
                        $itemPrice      = numberInd($sheetData[$i][$column[2]]);
                        $BranchCode     = $sheetData[$i][$column[3]];
                        /*=====================end=============================================================*/
                        if( (notCaseSensitifNotSpace($ItemCode)==""||notCaseSensitifNotSpace($ItemCode)==null) &&
                            (notCaseSensitifNotSpace($Currency)==""||notCaseSensitifNotSpace($Currency)==null) &&
                            ((notCaseSensitifNotSpace($itemPrice)=="")||(notCaseSensitifNotSpace($itemPrice)==null)||(notCaseSensitifNotSpace($itemPrice)*1<=0)) &&
                            ((notCaseSensitifNotSpace($BranchCode)=="")||(notCaseSensitifNotSpace($BranchCode)==null))    ){ //kalo null semua ga ada eksekusi sama sekali, dianggap baris kosong

                            //kalo null semua ga ada eksekusi sama sekali, dianggap baris kosong

                        }else if( ((notCaseSensitifNotSpace($ItemCode)=="")||notCaseSensitifNotSpace($ItemCode)==null)){
                            throw new Exception(noticesImport("denied", ["column"=>"Item Code","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else if((notCaseSensitifNotSpace($Currency)=="")||notCaseSensitifNotSpace($Currency)==null){
                            throw new Exception(noticesImport("denied", ["column"=>"Currency","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if((notCaseSensitifNotSpace($itemPrice)=="")||(notCaseSensitifNotSpace($itemPrice)==null)){
                            throw new Exception(noticesImport("denied", ["column"=>"Item Price","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(!checkNumberInd($itemPrice)){
                            throw new Exception(noticesImport("denied", ["column"=>"Item Price Bukan Angka/ Data ","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if ((notCaseSensitifNotSpace($BranchCode)=="")||(notCaseSensitifNotSpace($BranchCode)==null)){
                            throw new Exception(noticesImport("denied", ["column"=>"BranchCode","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(!$this->m_branchinfo->check_branch_exist($BranchCode)){
                            throw new Exception(noticesImport("notfound", ["column"=>"BranchCode","code"=>$BranchCode,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(!$this->m_itemprice->check_company_match($BranchCode)){
                            throw new Exception(noticesImport("notfound", ["column"=>"BranchCode","code"=>$BranchCode,"di"=>"Company ".$this->session->userdata("company"),"line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if(!$this->m_itemprice->check_code_exist($ItemCode, $BranchCode)){
                            throw new Exception(noticesImport("notfound", ["column"=>"Item Code","code"=>$ItemCode,"di"=>"inventories","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }
                        else if($this->m_currency->check_currency_exist($Currency, $BranchCode,$this->session->userdata('company')) == FALSE){
                            throw new Exception(noticesImport("notfound", ["column"=>"Currency","code"=>$Currency,"di"=>"Sistem","line"=>$i]));//pesan yang diambil dr helper : notices_import_file_helper.php
                        }else{
                            $data = array (
                                'BranchCode'    => $BranchCode,
                                'ItemCode'      => $ItemCode,
                                'ItemPrice'     => $itemPrice,
                                'CurrencyCode'  => $Currency,
                                'LastUser'      => $this->session->userdata("username")
                            );
                            //data sudah tersedia update kembali yang terbaru
                            if($this->m_itemprice->check_price_exist($ItemCode,$BranchCode,$Currency)){
                                $dataItemPrice['dataUpdate'][]  = $data;
                            }else{                                
                                //insert item price
                                $dataItemPrice['dataInsert'][]  = $data;
                            }
                        }                            
                    }
                    //sleep(8);
                    $rstTransEnd        = $this->m_itemprice->import_itemprice($dataItemPrice);
                    $result['status']   = $rstTransEnd['status'];
                    $result['message']  = $rstTransEnd['message'];   
                    echo json_encode($result);
                }else{          
                    throw new Exception(noticesImport("header",[]));//pesan yang diambil dr helper : notices_import_file_helper.php
                }
            }else{
                throw new Exception(noticesImport("not_choose",[]));//pesan yang diambil dr helper : notices_import_file_helper.php
            }		
	}
        catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }

    function import_templete(){
        $data = file_get_contents(APPPATH."import_templete/import_price_list.xlsx"); // Read the file's contents
        $name = 'import_price_list.xlsx';
    }
}
/* End of file import_price_list.php */
/* Location: ./application/modules_core/file/controllers/import_price_list.php */