<?php namespace App\Http\Controllers;

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

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

	    public function cbInit() {

			# START CONFIGURATION DO NOT REMOVE THIS LINE
			$this->title_field = "id";
			$this->limit = "20";
			$this->orderby = "id,desc";
			$this->global_privilege = false;
			$this->button_table_action = true;
			$this->button_bulk_action = false;
			$this->button_action_style = "button_icon";
			$this->button_edit = true;
			$this->button_delete = true;
			$this->button_detail = true;
			$this->button_show = false;
			if(CRUDBooster::myPrivilegeId()<>2){
			    $this->button_filter = true;
			    $this->button_add = true;
			}else{
			    $this->button_filter = false;
			    $this->button_add = false;
			}
			$this->button_import = false;
			$this->button_export = false;
			$this->table = "bahandap";
			# END CONFIGURATION DO NOT REMOVE THIS LINE

			# START COLUMNS DO NOT REMOVE THIS LINE
			$this->col = [];
			$this->col[] = ["label"=>"Kunci","name"=>"kunci","qrcode"=>true,"mainurl"=>"bjb.city"];
			//$this->col[] = ["label"=>"Kunci","name"=>"kunci"];
			$this->col[] = ["label"=>"Redirect url","name"=>"redurl"];
			$this->col[] = ["label"=>"File PDF","name"=>"file_pdf","download"=>"true"];
			
			//$this->col[] = ["label"=>"Owner","name"=>"owner","join"=>"cms_users,name"];
			
			$this->col[] = ["label"=>"Hit","name"=>"hit"];
			if(CRUDBooster::myPrivilegeId()<>2){
			    //$this->col[] = ["label"=>"Penandatangan","name"=>"penandatangan","join"=>"cms_users,name"];
			    $this->col[] = ["label"=>"Iframe","name"=>"iframe"];
			    //$this->col[] = ["label"=>"Conv ID","name"=>"conv_id","join"=>"waconv,chat_id"];
			    $this->col[] = ["label"=>"Hit Limit","name"=>"hit_limit"];
			    $this->col[] = ["label"=>"Updated By","name"=>"updated_by","join"=>"cms_users,name"];
			    $this->col[] = ["label"=>"Expired At","name"=>"expired_at"];
			}
			$this->col[] = ["label"=>"Updated At","name"=>"updated_at"];
			# END COLUMNS DO NOT REMOVE THIS LINE

			# START FORM DO NOT REMOVE THIS LINE
			$this->form = [];
			$this->form[] = ['label'=>'https://bjb.city/','name'=>'kunci','type'=>'text','validation'=>'required|min:4|max:255','width'=>'col-sm-6',"qrcode"=>true,"mainurl"=>"bjb.city","help"=>"*Minimal 4 karakter"];
			$this->form[] = ['label'=>'Redirect url','name'=>'redurl','type'=>'text','width'=>'col-sm-8',"help"=>"*Isian Ini akan diabaikan, Jika mengunggah file pdf pada isian 'File PDF' dibawah"];
			if(CRUDBooster::myPrivilegeId()<>2){
			    $this->form[] = ['label'=>'File PDF','name'=>'file_pdf','type'=>'upload','width'=>'col-sm-7','validation'=>'mimes:pdf'];
			   // $this->form[] = ['label'=>'Panandatangan','name'=>'penandatangan','type'=>'select2','width'=>'col-sm-4','datatable'=>'cms_users,name','datatable_where'=>'id_cms_privileges = 2'];
    			$this->form[] = ['label'=>'IFrame','name'=>'iframe','type'=>'radio','validation'=>'required','width'=>'col-sm-4','dataenum'=>'1|Yes;0|No','value'=>0];
    			$this->form[] = ['label'=>'Hit Limit','name'=>'hit_limit','type'=>'number','validation'=>'required|min:0','width'=>'col-sm-2','value'=>0,"help"=>"*0 untuk tidak terbatas"];
    			$this->form[] = ['label'=>'Expired At','name'=>'expired_at','type'=>'datetime','validation'=>'date_format:Y-m-d H:i:s','width'=>'col-sm-3'];
			}
// 			$this->form[] = ['label'=>'Updated At','name'=>'updated_at','type'=>'datamodal','validation'=>'integer|min:0','width'=>'col-sm-8','datamodal_table'=>'cms_users','datamodal_columns'=>'nik,name,email','datamodal_size'=>'small'];
			$this->form[] = ['label'=>'Updated By','name'=>'updated_by','type'=>'hidden','validation'=>'required|integer|min:0','width'=>'col-sm-8','value'=>CRUDBooster::myId()];
			
			# END FORM DO NOT REMOVE THIS LINE

			# OLD START FORM
			//$this->form = [];
			//$this->form[] = ["label"=>"Int","name"=>"int","type"=>"number","required"=>TRUE,"validation"=>"required|integer|min:0"];
			//$this->form[] = ["label"=>"Kunci","name"=>"kunci","type"=>"text","required"=>TRUE,"validation"=>"required|min:1|max:255"];
			//$this->form[] = ["label"=>"Redurl","name"=>"redurl","type"=>"textarea","required"=>TRUE,"validation"=>"required|string|min:5|max:5000"];
			//$this->form[] = ["label"=>"Iframe","name"=>"iframe","type"=>"text","required"=>TRUE,"validation"=>"required|min:1|max:255"];
			//$this->form[] = ["label"=>"Owner","name"=>"owner","type"=>"number","required"=>TRUE,"validation"=>"required|integer|min:0"];
			//$this->form[] = ["label"=>"Updated By","name"=>"updated_by","type"=>"number","required"=>TRUE,"validation"=>"required|integer|min:0"];
			//$this->form[] = ["label"=>"Expired At","name"=>"expired_at","type"=>"datetime","required"=>TRUE,"validation"=>"required|date_format:Y-m-d H:i:s"];
			# 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();


	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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'=>'Buka Link','icon'=>'fa fa-address-card','color'=>'info','url'=>'https://bjb.city/[kunci]'];


	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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()==2){
	            $this->index_button[] = ['label'=>'Tambah Link','url'=>CRUDBooster::mainpath("handap"),"icon"=>"fa fa-plus"];
	        }



	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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 genKunci(){
	        return "kunci";
	    }


	    /*
	    | ---------------------------------------------------------------------- 
	    | 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) {
	        if(CRUDBooster::myPrivilegeId() <> 1){
	            if(CRUDBooster::myPrivilegeId() == 2 ){
	                $query->where('gen',0)->where('updated_by',CRUDBooster::myId());
	           // }elseif(CRUDBooster::myPrivilegeId() == 13){
	           //     $query->where('gen',0);
	            }else{
	                $query->where('gen',0)->where('updated_by',CRUDBooster::myId())->orWhere('updated_by_priv',CRUDBooster::myPrivilegeId());
	            }
	        }
	            
	    }

	    /*
	    | ---------------------------------------------------------------------- 
	    | 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) {        
	        if($postdata['file_pdf']){
	            unset($postdata['redurl']);
	        }
	        //dd($postdata);
            $exist = DB::table('bahandap')
                ->where('kunci',$postdata['kunci'])->get();
                     
            if(sizeof($exist)>0){
                CRUDBooster::redirectBack("Link tidak tersedia !");
            }else{
                if(CRUDBooster::myPrivilegeId()==2){
                    $mylink = DB::table('bahandap')->where('updated_by',CRUDBooster::myId())->count();
                    if($mylink>=3){
                        CRUDBooster::redirectBack("link melebihi batas ! Anda bisa menghapus link sebelumnya");
                    }
                }
            }
            
	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command after add public static function called 
	    | ---------------------------------------------------------------------- 
	    | @id = last insert id
	    | 
	    */
	    public function hook_after_add($id) {        
	        //Your code here

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate data input before update data is execute
	    | ---------------------------------------------------------------------- 
	    | @postdata = input post data 
	    | @id       = current id 
	    | 
	    */
	    public function hook_before_edit(&$postdata,$id) {        
	        if($postdata['file_pdf']){
	            unset($postdata['redurl']);
	        }
	        $ori = DB::table('bahandap')
                     ->where('id',$id)->first();
                     
            $exist = DB::table('bahandap')
                     ->where('kunci',$postdata['kunci'])->get();
                    
                     
            if(sizeof($exist)>0 && $exist[0]->kunci != $ori->kunci ){
                return CRUDBooster::redirectBack("Link tidak tersedia !");
            }

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | 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

	    }

        public function getHandap() {
	        //Your code here
	        $data = [];
            return view('bahandap.index',$data);
	    }
	    
	    public function postHandap() {
	       // dd($this->cekurl(Request::input('redurl')));
	        if(strlen(Request::input('kunci'))>3 ){
	            if (filter_var(Request::input('redurl'), FILTER_VALIDATE_URL) === FALSE) {
                    CRUDBooster::redirectBack("URL '" . Request::input('redurl') . "' Tidak valid (sertakan http/https)");
                //}elseif ($this->cekurl(Request::input('redurl')) === FALSE) {
                  //  CRUDBooster::redirectBack("URL '" . Request::input('redurl') . "' Tidak dapat di akses");
                }else{
        	        $exist = DB::table('bahandap')
                        ->where('kunci',Request::input('kunci'))->get();
                             
                    if(sizeof($exist)>0){
                        CRUDBooster::redirectBack("Link 'https://bjb.city/" . Request::input('kunci') . "' sudah ada !");
                    }else{
                        if(CRUDBooster::myPrivilegeId()==2){
                            $mylink = DB::table('bahandap')->where('gen',0)->where('updated_by',CRUDBooster::myId())->count();
                            if($mylink>=3){
                                CRUDBooster::redirectBack("Link melebihi batas ! Tekan tombol LINK SAYA");
                            }
                        }
                        
                        DB::table('bahandap')->insert(['kunci'=>Request::input('kunci'),'redurl'=>Request::input('redurl'),'hit_limit'=>0,'updated_by'=>CRUDBooster::myId()]);
                        
                        return redirect(CRUDBooster::mainpath())->with(['message' => "Link BAHANDAP Berhasil ditambahkan", 'message_type' => "success"]);
                    }
                }
	        }else{
	            CRUDBooster::redirectBack("Minimal 6 karakter !");
	        }
	    }
	    
	    public function cekurl($url){
	       // Use curl_init() function to initialize a cURL session
            $curl = curl_init($url);
              
            // Use curl_setopt() to set an option for cURL transfer
            curl_setopt($curl, CURLOPT_NOBODY, true);
              
            // Use curl_exec() to perform cURL session
            $result = curl_exec($curl);
              
            if ($result !== false) {
                  
                // Use curl_getinfo() to get information
                // regarding a specific transfer
                $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
                
                if ($statusCode == 404) {
                    return false;
                }
                else {
                    return true;
                }
            }
            else {
                return false;
            }
	    }

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


	}