<?php namespace App\Http\Controllers;

	use Session;
	use Request;
	use DB;
	use CRUDBooster;

	class AdminUmkmPemilikController extends \crocodicstudio\crudbooster\controllers\CBController {

	    public function cbInit() {

			# START CONFIGURATION DO NOT REMOVE THIS LINE
			$this->title_field = "warga_bjb_id";
			$this->limit = "20";
			$this->orderby = "id,desc";
			$this->global_privilege = false;
			$this->button_table_action = true;
			$this->button_bulk_action = true;
			$this->button_action_style = "button_icon";
			$this->button_add = true;
			$this->button_edit = true;
			$this->button_delete = true;
			$this->button_detail = true;
			$this->button_show = false;
			$this->button_filter = true;
			$this->button_import = false;
			$this->button_export = true;
			$this->table = "umkm_pemilik";
			# END CONFIGURATION DO NOT REMOVE THIS LINE

			# START COLUMNS DO NOT REMOVE THIS LINE
			$this->col = [];
			
			$this->col[] = ["label"=>"NIK","name"=>"warga_bjb_id","join"=>"warga_bjb,nik"];
			$this->col[] = ["label"=>"Nama","name"=>"warga_bjb_id","join"=>"warga_bjb,nama_lgkp"];
			$this->col[] = ["label"=>"Alamat","name"=>"warga_bjb_id","join"=>"warga_bjb,alamat2"];
			$this->col[] = ["label"=>"No IUMK","name"=>"no_iumk"];
			//$this->col[] = ["label"=>"No NPWP","name"=>"no_npwp"];
			$this->col[] = ["label"=>"No Telepon","name"=>"no_telp"];
			$this->col[] = ["label"=>"Updated by","name"=>"updated_by","join"=>"cms_users,name"];
			# END COLUMNS DO NOT REMOVE THIS LINE

			# START FORM DO NOT REMOVE THIS LINE
			$warga_id=CRUDBooster::findWargaFromPemilik(CRUDBooster::getCurrentId());
			
			$this->form = [];
			if(CRUDBooster::MyPrivilegeId()==2){
			    $this->form[] = ['label'=>'NIK','name'=>'warga_bjb_id','type'=>'hidden','validation'=>'integer|min:0','width'=>'col-sm-6','value'=>CRUDBooster::menik(CRUDBooster::me()->nik)->id];
			    //$this->form[] = ['label'=>'NIK','name'=>'warga_bjb_id','type'=>'datamodal','validation'=>'required|min:1|max:255','width'=>'col-sm-8','datamodal_table'=>'warga_bjb','datamodal_columns'=>'nik,nama_lgkp,tmpt_lhr,tgl_lhr,alamat','datamodal_size'=>'large','datamodal_columns_alias_name'=>'NIK','Nama Lengkap','Tempat Lahir','Tanggal Lahir','value'=>CRUDBooster::menik(CRUDBooster::me()->nik)->id];
			}else{
			    $this->form[] = ['label'=>'NIK','name'=>'warga_bjb_id','type'=>'datamodal','validation'=>'required|min:1|max:255','width'=>'col-sm-8','datamodal_table'=>'warga_bjb','datamodal_columns'=>'nik,nama_lgkp,tmpt_lhr,tgl_lhr,alamat','datamodal_size'=>'large','datamodal_columns_alias'=>"NIK,Nama Lengkap,Tempat Lahir,Tanggal Lahir"];
			}
			
			$this->form[] = ['label'=>'Nomor IUMK','name'=>'no_iumk','type'=>'text','validation'=>'min:1|max:255','width'=>'col-sm-6'];
			$this->form[] = ['label'=>'Nomor NPWP','name'=>'no_npwp','type'=>'text','validation'=>'min:1|max:255','width'=>'col-sm-6'];
			$this->form[] = ['label'=>'Nomor Telepon','name'=>'no_telp','type'=>'text','validation'=>'required|numeric','width'=>'col-sm-6'];
			$this->form[] = ['label'=>'Fax','name'=>'fax','type'=>'text','validation'=>'numeric','width'=>'col-sm-6','placeholder'=>'Anda hanya dapat memasukkan angka saja'];
			$this->form[] = ['label'=>'Email','name'=>'email','type'=>'email','validation'=>'min:1|max:255|email|unique:umkm_pemilik','width'=>'col-sm-6'];
			$this->form[] = ['label'=>'Facebook','name'=>'facebook_id','type'=>'text','validation'=>'min:1|max:255','width'=>'col-sm-6'];
			$this->form[] = ['label'=>'Instagram','name'=>'instagram_id','type'=>'text','validation'=>'min:1|max:255','width'=>'col-sm-6'];
			//$this->id = $id;
			//$this->form[] = ['label'=>'Pelatihan','name'=>'pelatihan','type'=>'checkbox','validation'=>'min:1|max:255','width'=>'col-sm-6','datatable'=>'umkm_pelatihan,nama_pelatihan'];
			
			//var_dump($form);
// 			if(CRUDBooster::getCurrentMethod()=="getEdit"){
//     			$columns[] = ['label'=>'Tanggal','name'=>'tanggal','type'=>'datetime']; 
//     			$columns[] = ['label'=>'Pelatihan','name'=>'pelatihan_id','type'=>'select','validation'=>'min:1|max:255','width'=>'col-sm-4','datatable'=>'umkm_pelatihan,nama_pelatihan'];
//     		    $columns[] = ['label'=>'Keterangan','name'=>'keterangan','type'=>'textarea'];
    		    
//     		    //$warga_id=CRUDBooster::findWargaFromPemilik(CRUDBooster::getCurrentId());
//     		    //$columns[] = ['label'=>'Warga ID','name'=>'warga_bjb_id','type'=>'text','validation'=>'min:1|max:255','width'=>'col-sm-4','value'=>$id];
//     			$this->form[] = ['label'=>'History Pelatihan','name'=>'history_pelatihan','type'=>'child','columns'=>$columns,'width'=>'col-sm-6','table'=>'history_pelatihan','parent'=>'umkm_pemilik','foreign_key'=>'umkm_pemilik_id'];
// 			}
			
			//$this->form[] = ['label'=>'Penerima Bantuan','name'=>'bantuan','type'=>'checkbox','validation'=>'min:1|max:255','width'=>'col-sm-10','datatable'=>'umkm_bantuan,bantuan'];
			$this->form[] = ['label'=>'Keterangan','name'=>'keterangan','type'=>'textarea','validation'=>'string|min:5|max:5000','width'=>'col-sm-8'];
			$this->form[] = ['label'=>'Status UMKM','name'=>'status_umkm_id','type'=>'select2','validation'=>'integer|min:0','width'=>'col-sm-6','datatable'=>'umkm_status,status'];
			$this->form[] = ['label'=>'Updated by','name'=>'updated_by','type'=>'hidden','validation'=>'integer|min:0','width'=>'col-sm-6','value'=>CRUDBooster::myId()];
			
			
			# END FORM DO NOT REMOVE THIS LINE

			# OLD START FORM
			//$this->form = [];
			//$this->form[] = ['label'=>'NIK','name'=>'nik_owner','type'=>'datamodal','validation'=>'required|min:1|max:255','width'=>'col-sm-10','datamodal_table'=>'warga_bjb','datamodal_columns'=>'nik,nama_lgkp,tmpt_lhr,tgl_lhr','datamodal_size'=>'large','datamodal_columns_alias_name'=>'\'NIK\',\'Nama Lengkap\',\'Tempat Lahir\',\'Tanggal Lahir\''];
			//$this->form[] = ['label'=>'Nomor IUMK','name'=>'no_iumk','type'=>'text','validation'=>'required|min:1|max:255','width'=>'col-sm-10'];
			//$this->form[] = ['label'=>'Nomor NPWP','name'=>'no_npwp','type'=>'text','validation'=>'required|min:1|max:255','width'=>'col-sm-10'];
			//$this->form[] = ['label'=>'Nomor Telepon','name'=>'no_telp','type'=>'number','validation'=>'required|numeric','width'=>'col-sm-10'];
			//$this->form[] = ['label'=>'Fax','name'=>'fax','type'=>'number','validation'=>'numeric','width'=>'col-sm-10','placeholder'=>'Anda hanya dapat memasukkan angka saja'];
			//$this->form[] = ['label'=>'Email','name'=>'email','type'=>'email','validation'=>'min:1|max:255|email|unique:umkm_pemilik','width'=>'col-sm-10'];
			//$this->form[] = ['label'=>'Facebook','name'=>'facebook_id','type'=>'text','validation'=>'min:1|max:255','width'=>'col-sm-10'];
			//$this->form[] = ['label'=>'Instagram','name'=>'instagram_id','type'=>'text','validation'=>'min:1|max:255','width'=>'col-sm-10'];
			//$this->form[] = ['label'=>'Pelatihan','name'=>'pelatihan','type'=>'checkbox','validation'=>'min:1|max:255','width'=>'col-sm-10','datatable'=>'umkm_pelatihan,nama_pelatihan'];
			//$this->form[] = ['label'=>'Keterangan','name'=>'keterangan','type'=>'textarea','validation'=>'string|min:5|max:5000','width'=>'col-sm-10'];
			//$this->form[] = ['label'=>'Status UMKM','name'=>'status_umkm_id','type'=>'select2','validation'=>'integer|min:0','width'=>'col-sm-6'];
			# OLD END FORM

			/* 
	        | ---------------------------------------------------------------------- 
	        | Sub Module
	        | ----------------------------------------------------------------------     
			| @label          = Label of action 
			| @path           = Path of sub module
			| @foreign_key 	  = foreign key of sub table/module
			| @button_color   = Bootstrap Class (primary,success,warning,danger)
			| @button_icon    = Font Awesome Class  
			| @parent_columns = Sparate with comma, e.g : name,created_at
	        | 
	        */
	        $this->sub_module = array();
	        //$this->sub_module[] = ['label'=>'List Usaha','path'=>'umkm_usaha','parent_columns'=>'warga_bjb_id','foreign_key'=>'warga_bjb_id','button_color'=>'success','button_icon'=>'fa fa-bars'];


	        /* 
	        | ---------------------------------------------------------------------- 
	        | Add More Action Button / Menu
	        | ----------------------------------------------------------------------     
	        | @label       = Label of action 
	        | @url         = Target URL, you can use field alias. e.g : [id], [name], [title], etc
	        | @icon        = Font awesome class icon. e.g : fa fa-bars
	        | @color 	   = Default is primary. (primary, warning, succecss, info)     
	        | @showIf 	   = If condition when action show. Use field alias. e.g : [id] == 1
	        | 
	        */
	        $this->addaction = array();
	        $this->addaction[] = ['label'=>'List Usaha','icon'=>'fa fa-address-card','color'=>'success','url'=>'https://siapkk.banjarbarukota.go.id/admin/umkm_usaha?return_url=https%3A%2F%2Fsiapkk.banjarbarukota.go.id%2Fadmin%2Fumkm_pemilik&parent_table=umkm_pemilik&parent_columns=warga_bjb_id&parent_columns_alias=&parent_id=[warga_bjb_id]&foreign_key=warga_bjb_id&label=Pemilik'];


	        /* 
	        | ---------------------------------------------------------------------- 
	        | Add More Button Selected
	        | ----------------------------------------------------------------------     
	        | @label       = Label of action 
	        | @icon 	   = Icon from fontawesome
	        | @name 	   = Name of button 
	        | Then about the action, you should code at actionButtonSelected method 
	        | 
	        */
	        $this->button_selected = array();

	                
	        /* 
	        | ---------------------------------------------------------------------- 
	        | Add alert message to this module at overheader
	        | ----------------------------------------------------------------------     
	        | @message = Text of message 
	        | @type    = warning,success,danger,info        
	        | 
	        */
	        $this->alert        = array();
	                

	        
	        /* 
	        | ---------------------------------------------------------------------- 
	        | Add more button to header button 
	        | ----------------------------------------------------------------------     
	        | @label = Name of button 
	        | @url   = URL Target
	        | @icon  = Icon from Awesome.
	        | 
	        */
	        $this->index_button = array();
	         if(CRUDBooster::myPrivilegeId()==14){
	            $this->index_button[] = ['label'=>'Import file excell', 'url'=>CRUDBooster::adminPath('umkm_pemilik/pilih-file'),'icon'=>'fa fa-arrow-down'];
	        }



	        /* 
	        | ---------------------------------------------------------------------- 
	        | Customize Table Row Color
	        | ----------------------------------------------------------------------     
	        | @condition = If condition. You may use field alias. E.g : [id] == 1
	        | @color = Default is none. You can use bootstrap success,info,warning,danger,primary.        
	        | 
	        */
	        $this->table_row_color = array();     	          

	        
	        /*
	        | ---------------------------------------------------------------------- 
	        | You may use this bellow array to add statistic at dashboard 
	        | ---------------------------------------------------------------------- 
	        | @label, @count, @icon, @color 
	        |
	        */
	        $this->index_statistic = array();



	        /*
	        | ---------------------------------------------------------------------- 
	        | Add javascript at body 
	        | ---------------------------------------------------------------------- 
	        | javascript code in the variable 
	        | $this->script_js = "function() { ... }";
	        |
	        */
	        $this->script_js = NULL;


            /*
	        | ---------------------------------------------------------------------- 
	        | Include HTML Code before index table 
	        | ---------------------------------------------------------------------- 
	        | html code to display it before index table
	        | $this->pre_index_html = "<p>test</p>";
	        |
	        */
	        $this->pre_index_html = null;
	        
	        
	        
	        /*
	        | ---------------------------------------------------------------------- 
	        | Include HTML Code after index table 
	        | ---------------------------------------------------------------------- 
	        | html code to display it after index table
	        | $this->post_index_html = "<p>test</p>";
	        |
	        */
	        $this->post_index_html = null;
	        
	        
	        
	        /*
	        | ---------------------------------------------------------------------- 
	        | Include Javascript File 
	        | ---------------------------------------------------------------------- 
	        | URL of your javascript each array 
	        | $this->load_js[] = asset("myfile.js");
	        |
	        */
	        $this->load_js = array();
	        
	        
	        
	        /*
	        | ---------------------------------------------------------------------- 
	        | Add css style at body 
	        | ---------------------------------------------------------------------- 
	        | css code in the variable 
	        | $this->style_css = ".style{....}";
	        |
	        */
	        $this->style_css = NULL;
	        
	        
	        
	        /*
	        | ---------------------------------------------------------------------- 
	        | Include css File 
	        | ---------------------------------------------------------------------- 
	        | URL of your css each array 
	        | $this->load_css[] = asset("myfile.css");
	        |
	        */
	        $this->load_css = array();
	        
	        
	    }
	    
	    public function getPilihFile(){
	           $data=[];
	           $data['uploaded']=DB::table('uploaded')
	                            ->join('cms_users','cms_users.id','uploaded.updated_by')
	                            ->join('cms_privileges','cms_privileges.id','uploaded.updated_by_priv')
	                            ->where('updated_by_priv',CRUDBooster::myPrivilegeId())
	                            ->selectRaw('uploaded.*,cms_users.name as nama_user, cms_privileges.name as role')
	                            ->get();
	           
	           return view('import.pilih',$data);
	     }
	     
	     public function getImportFile($id){
	        $uploaded=DB::table('uploaded')->where('id',$id)->first();
	        $data['id']=$id;
	        $data['excel']=$uploaded->file;
	       // if(strlen($bantuan->upload_file)>0){
                 $this->cbView('import.xlsx',$data);
	    //    }else{
	            
	      //  }
	    }
	    
	    public function postImportExcel($id){
	        $selected_kolom=Request::input('selected_kolom');
	        $rows=Session::get('rows');
	        $excel=Request::input('excel');
	        $result = array();
	        
	        $pencarian=0;
	        $ketemu=0;
	        $baru=0;
	        $sudah=0;
	        $tidakketemu=0;
	        $capilyes=0;
	        $capilno=0;
	       
        	foreach($rows as $ro){
        	    $pencarian++;
        	    $isi =[];
        	    $found=DB::table('warga_bjb')->where('nik',$ro[$selected_kolom])->first();
        	    if($found){
        	        //var_dump( $selected_kolom . '-' .$ro[$selected_kolom] );
        	        $ketemu++;
        	        $exists=DB::table('umkm_pemilik')->where('warga_bjb_id',$found->id)->first();
        	        
        	        if($exists){
        	            $sudah++;
        	            $isi['status'] = 0;
        	            $isi['message'] = $ro[$selected_kolom] . ' data sudah ada';
                	    array_push($result, json_encode($isi) );
        	        }else{
        	            $baru++;
        	            DB::table('umkm_pemilik')->insert(['warga_bjb_id'=>$found->id,'no_telp'=>$ro['NO. HP/WA'], 'updated_by'=>CRUDBooster::myId(),'updated_by'=>CRUDBooster::myId()]);
        	            $isi['status'] = 1;
        	            $isi['message'] =  $ro[$selected_kolom] . ' ditambahkan  - detail ('. implode(",",$ro) . ')';
                	    array_push($result, json_encode($isi) );
        	        }

        	        
        	    }else{
        	        $tidakketemu++;
        	        $isi['status'] = 2;
    	            $isi['message'] =  $ro[$selected_kolom] . ' Tidak Ditemukan ! - detail ('. implode(",",$ro) . ')' ;
            	    array_push($result, json_encode($isi) );
        	       // $capil = CRUDBooster::updateNik($ro[$selected_kolom]);
        	       // if($capil->api_status=="1"){
        	       //     $capilyes++;
        	       //     array_push($result, $ro[$selected_kolom] . '-' .$ro['NAMA_PENERIMA'] . ' ada dalam data capil !'   );
        	       //    // $found2=DB::table('warga_bjb')->where('nik',$ro[$selected_kolom])->first();
        	       //    // DB::table('history_bantuan')->insert(['tanggal'=>now(),'warga_bjb_id'=>$found2->id,'bantuan_id'=>$id,'keterangan'=>'Import dari file '.$excel,'updated_by'=>CRUDBooster::myId(),'updated_by_priv'=>CRUDBooster::myPrivilegeId()]);
        	       //    // array_push($result, $ro[$selected_kolom] . ' ditambahkan' );
        	       //     //array_push($result, json_encode($capil)  );
        	       // }else{
        	       //     $capilno++;
        	       //     array_push($result, $ro[$selected_kolom] . '-' .$ro['NAMA_PENERIMA'] . ' Tidak teregistrasi !'   );
        	       // }
        	    }
        	}
        	DB::table('uploaded')->where('id',$id)->update(['logs'=>$pencarian. ' pencarian, '.$ketemu. ' nik ditemukan, '. $baru . ' ditambahkan, '. $sudah . ' sudah ada, '. $tidakketemu . ' nik tidak ditemukan, ' . $capilyes . ' diambil di capil, ' . $capilno . ' tidak teregister.']);
        	$isi['message'] = $pencarian. ' pencarian, '.$ketemu. ' nik ditemukan, '. $baru . ' ditambahkan, '. $sudah . ' sudah ada, '. $tidakketemu . ' nik tidak ditemukan, ' . $capilyes . ' diambil di capil, ' . $capilno . ' tidak teregister.';
        	array_push($result, json_encode($isi));
	        $data['result'] = $result;
	        $this->cbView('import.result',$data);
	    }


	    /*
	    | ---------------------------------------------------------------------- 
	    | Hook for button selected
	    | ---------------------------------------------------------------------- 
	    | @id_selected = the id selected
	    | @button_name = the name of button
	    |
	    */
	    public function actionButtonSelected($id_selected,$button_name) {
	        //Your code here
	            
	    }


	    /*
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate query of index result 
	    | ---------------------------------------------------------------------- 
	    | @query = current sql query 
	    |
	    */
	    public function hook_query_index(&$query) {
	        //Your code here
	            
	    }

	    /*
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate row of index table html 
	    | ---------------------------------------------------------------------- 
	    |
	    */    
	    public function hook_row_index($column_index,&$column_value) {	        
	    	//Your code here
	    	
	    }

	    /*
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate data input before add data is execute
	    | ---------------------------------------------------------------------- 
	    | @arr
	    |
	    */
	    public function hook_before_add(&$postdata) {        
	        //Your code here
           $exist = DB::table($this->table)
                     ->where('warga_bjb_id',$postdata['warga_bjb_id'])->get();
                     
            if(sizeof($exist)>0){
                return CRUDBooster::redirectBack("NIK sudah terdaftar !");
            }
	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command after add public static function called 
	    | ---------------------------------------------------------------------- 
	    | @id = last insert id
	    | 
	    */
	    public function hook_after_add($id) {      
	        
	        //$usaha = DB::table('umkm_pemilik')->where('id',$id)->first();
	        
	        //return redirect('https://siapkk.banjarbarukota.go.id/admin/umkm_usaha?return_url=https%3A%2F%2Fsiapkk.banjarbarukota.go.id%2Fadmin%2Fumkm_pemilik%3Fq%3DGINANJAR&parent_table=umkm_pemilik&parent_columns=warga_bjb_id&parent_columns_alias=&parent_id='.$usaha->warga_bjb_id.'&foreign_key=warga_bjb_id&label=List+Usaha');

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate data input before update data is execute
	    | ---------------------------------------------------------------------- 
	    | @postdata = input post data 
	    | @id       = current id 
	    | 
	    */
	    public function hook_before_edit(&$postdata,$id) {        
	        //Your code here
            $ori = DB::table($this->table)
                     ->where('id',$id)->first();
                     
            $exist = DB::table($this->table)
                     ->where('warga_bjb_id',$postdata['warga_bjb_id'])->get();
                    
                     
            if(sizeof($exist)>0 && $exist[0]->warga_bjb_id != $ori->warga_bjb_id ){
                return CRUDBooster::redirectBack("Nik sudah terdaftar !");
            }
	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command after edit public static function called
	    | ----------------------------------------------------------------------     
	    | @id       = current id 
	    | 
	    */
	    public function hook_after_edit($id) {
	        //Your code here 

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command before delete public static function called
	    | ----------------------------------------------------------------------     
	    | @id       = current id 
	    | 
	    */
	    public function hook_before_delete($id) {
	        //Your code here

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command after delete public static function called
	    | ----------------------------------------------------------------------     
	    | @id       = current id 
	    | 
	    */
	    public function hook_after_delete($id) {
	        //Your code here

	    }



	    //By the way, you can still create your own method in here... :) 


	}