<?php namespace App\Http\Controllers;

	use Session;
	use Request;
	use DB;
	use CRUDBooster;
	use PDF;
	use App\Signature\Esign;
	use App\Signature\Client\BasicRest;

	class AdminTteController 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 = true;
			$this->button_action_style = "button_icon";
			$this->button_add = false;
			$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 = false;
			$this->table = "idv_data";
			# END CONFIGURATION DO NOT REMOVE THIS LINE

			# START COLUMNS DO NOT REMOVE THIS LINE
			$this->col = [];
			$this->col[] = ["label"=>"Status","name"=>"idv_data.status_id","join"=>"status_surat,status"];
			$this->col[] = ["label"=>"Pengirim","name"=>"parent_id","join"=>"dokumen,nomor_surat"];
			$this->col[] = ["label"=>"Pengirim","name"=>"parent_id","join"=>"dokumen,pengirim"];
			$this->col[] = ["label"=>"Perihal","name"=>"parent_id","join"=>"dokumen,perihal"];
			//$this->col[] = ["label"=>"Perihal","name"=>"dokumen.perihal"];
		//	$this->col[] = ["label"=>"Draft","name"=>"parent_id","join"=>"dokumen,docx_file","download"=>true];
			$this->col[] = ["label"=>"Pdf","name"=>"parent_id","join"=>"dokumen,pdf_file","download"=>true];
		//	$this->col[] = ["label"=>"Signed Pdf","name"=>"parent_id","join"=>"dokumen,signed_file","download"=>true];
			$this->col[] = ["label"=>"Admin","name"=>"cms_users_id","join"=>"cms_users,name"];
			$this->col[] = ["label"=>"Tag Esign","name"=>"tag_to_sign"];
			# END COLUMNS DO NOT REMOVE THIS LINE

			# START FORM DO NOT REMOVE THIS LINE
			$this->form = [];
			$this->form[] = ['label'=>'Status Id','name'=>'status_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'status_surat,status'];
			$this->form[] = ['label'=>'Tag To Sign','name'=>'tag_to_sign','type'=>'text','validation'=>'required|min:1|max:255','width'=>'col-sm-10'];
			# END FORM DO NOT REMOVE THIS LINE

			# OLD START FORM
			//$this->form = [];
			//$this->form[] = ["label"=>"Parent Table","name"=>"parent_table","type"=>"text","required"=>TRUE,"validation"=>"required|min:1|max:255"];
			//$this->form[] = ["label"=>"Parent Id","name"=>"parent_id","type"=>"select2","required"=>TRUE,"validation"=>"required|integer|min:0","datatable"=>"parent,id"];
			//$this->form[] = ["label"=>"Status Id","name"=>"status_id","type"=>"select2","required"=>TRUE,"validation"=>"required|integer|min:0","datatable"=>"status,id"];
			//$this->form[] = ["label"=>"Cms Users Id","name"=>"cms_users_id","type"=>"select2","required"=>TRUE,"validation"=>"required|integer|min:0","datatable"=>"cms_users,name"];
			//$this->form[] = ["label"=>"Tag To Sign","name"=>"tag_to_sign","type"=>"text","required"=>TRUE,"validation"=>"required|min:1|max:255"];
			# 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'=>'Baca','icon'=>'fa fa-address-card','color'=>'info','url'=>CRUDBooster::mainpath('preview-tte').'/[parent_id]/[id]']; //,'showIf'=>'[rekomendasi_by]<>""']; //.$this->pejabat->id];


	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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();
	        $this->button_selected[] = ['label'=>'Tandatangani Terpilih','icon'=>'fa fa-check','name'=>'tandatangani_terpilih'];

	                
	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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();
	        $this->index_button[] = ['label'=>'Semua','color'=>'primary','url'=>CRUDBooster::adminPath('tte')];
	        $this->index_button[] = ['label'=>'Baru','color'=>'info','url'=>CRUDBooster::adminPath().'/tte?filter_column%5Bstatus_surat.status%5D%5Btype%5D=%3D&filter_column%5Bstatus_surat.status%5D%5Bvalue%5D=Baru&filter_column%5Bstatus_surat.status%5D%5Bsorting%5D=&filter_column%5Bdokumen.perihal%5D%5Btype%5D=&filter_column%5Bdokumen.perihal%5D%5Bsorting%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Btype%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Bsorting%5D=&lasturl=https%3A%2F%2Fsiapkk.banjarbarukota.go.id%2Fadmin%2Ftte'];
            $this->index_button[] = ['label'=>'Diproses','color'=>'warning','url'=>CRUDBooster::adminPath().'/tte?filter_column%5Bstatus_surat.status%5D%5Btype%5D=%3D&filter_column%5Bstatus_surat.status%5D%5Bvalue%5D=Diproses&filter_column%5Bstatus_surat.status%5D%5Bsorting%5D=&filter_column%5Bdokumen.perihal%5D%5Btype%5D=&filter_column%5Bdokumen.perihal%5D%5Bsorting%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Btype%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Bsorting%5D=&lasturl=https%3A%2F%2Fsiapkk.banjarbarukota.go.id%2Fadmin%2Ftte'];
            $this->index_button[] = ['label'=>'Ditolak','color'=>'danger','url'=>CRUDBooster::adminPath().'/tte?filter_column%5Bstatus_surat.status%5D%5Btype%5D=%3D&filter_column%5Bstatus_surat.status%5D%5Bvalue%5D=Ditolak&filter_column%5Bstatus_surat.status%5D%5Bsorting%5D=&filter_column%5Bdokumen.perihal%5D%5Btype%5D=&filter_column%5Bdokumen.perihal%5D%5Bsorting%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Btype%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Bsorting%5D=&lasturl=https%3A%2F%2Fsiapkk.banjarbarukota.go.id%2Fadmin%2Ftte'];
            $this->index_button[] = ['label'=>'Selesai','color'=>'success','url'=>CRUDBooster::adminPath().'/tte?filter_column%5Bstatus_surat.status%5D%5Btype%5D=%3D&filter_column%5Bstatus_surat.status%5D%5Bvalue%5D=Selesai&filter_column%5Bstatus_surat.status%5D%5Bsorting%5D=&filter_column%5Bdokumen.perihal%5D%5Btype%5D=&filter_column%5Bdokumen.perihal%5D%5Bsorting%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Btype%5D=&filter_column%5Bidv_data.tag_to_sign%5D%5Bsorting%5D=&lasturl=https%3A%2F%2Fsiapkk.banjarbarukota.go.id%2Fadmin%2Ftte'];

	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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();    
	        $this->table_row_color[] = ['condition'=>'[status_id] == 1','color'=>'info'];
	        $this->table_row_color[] = ['condition'=>'[status_id] == 3','color'=>'warning'];
	        $this->table_row_color[] = ['condition'=>'[status_id] == 4','color'=>'danger'];

	        
	        /*
	        | ---------------------------------------------------------------------- 
	        | You may use this bellow array to add statistic at dashboard 
	        | ---------------------------------------------------------------------- 
	        | @label, @count, @icon, @color 
	        |
	        */
	        $this->index_statistic = array();
            // $this->index_statistic[] = ['label'=>'Belum dibaca','count'=>DB::table($this->table)->where('status_id',1)->count(),'icon'=>'fa fa-inbox','color'=>'blue','width'=>'col-sm-3'];
            // $this->index_statistic[] = ['label'=>'Diproses','count'=>DB::table($this->table)->where('status_id',3)->count(),'icon'=>'fa fa-inbox','color'=>'yellow','width'=>'col-sm-3'];
            // $this->index_statistic[] = ['label'=>'Ditolak','count'=>DB::table($this->table)->where('status_id',4)->count(),'icon'=>'fa fa-inbox','color'=>'red','width'=>'col-sm-3'];
            // $this->index_statistic[] = ['label'=>'Ditandatangani','count'=>DB::table($this->table)->where('status_id',5)->count(),'icon'=>'fa fa-inbox','color'=>'green','width'=>'col-sm-3'];


	        /*
	        | ---------------------------------------------------------------------- 
	        | 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();
	        
	        
	    }


	    /*
	    | ---------------------------------------------------------------------- 
	    | Hook for button selected
	    | ---------------------------------------------------------------------- 
	    | @id_selected = the id selected
	    | @button_name = the name of button
	    |
	    */
	    public function actionButtonSelected($id_selected,$button_name) {
	       if($button_name == 'tandatangani_terpilih') {
	          

           }
	            
	    }
	    
	    
	    public function getPreviewTte($parent_id,$id) {
	        
	        $data = [];
	        $data['id'] = $parent_id;
	        $data['idv_id'] = $id;
	        $data['batal'] = 'tte';
	        $data['surat'] = DB::table('dokumen')->where('id',$parent_id)->first();
	        DB::table('idv_data')->where('id',$id)->where('status_id',0)->update(['status_id'=>2]);
	        $data['idv'] = DB::table('idv_data')->where('id',$id)->first();
	        
	       // dd($data['surat']->pdf_file);
	       if($data['idv']->signed_pdf && $data['surat']->pdf_file){
	            $data['pdf_path'] = $data['idv']->signed_pdf;
	            $data['signed'] = 0;
	            
	            return view('pdf.preview',$data);
	       }
	        if($data['surat']->pdf_file && !$data['idv']->signed_pdf){
	            $data['pdf_path'] = $data['surat']->pdf_file;
	            $data['signed'] = 0;
	            
	            return view('pdf.preview',$data);
	        }
	         if(!$data['surat']->pdf_file && !$data['idv']->signed_pdf){
	            CRUDBooster::redirectBack("File PDF tidak tersedia !", "danger");
	        }
	    }
	    
	    public function getProses($id) {
	        DB::table('idv_data')->where('parent_table','dokumen')->where('id',$id)->update(['status_id'=>3]);
            
            CRUDBooster::redirect(CRUDBooster::mainpath(),"Dokumen diproses","success");
	    }
	    
	    public function getTolak($id) {
	        DB::table('idv_data')->where('parent_table','dokumen')->where('id',$id)->update(['status_id'=>4]);
            
            CRUDBooster::redirect(CRUDBooster::mainpath(),"Dokumen ditolak","info");
	    }
	    
	    public function postTte(){
	        $data = [];
	        $data['surat'] = DB::table('dokumen')->where('id',Request::input('id'))->first();
	        $idv = DB::table('idv_data')->where('id',Request::input('idv_id'))->where('parent_table','dokumen')->first();
            
	        $esign = new Esign();
            $resp = $esign->sign($nik = CRUDBooster::me()->nik, $pass = Request::input('pass'), $doc = $data['surat']->pdf_file, $tag = $idv->tag_to_sign, $imageTTD = CRUDBooster::me()->spesimen_tte);
            $response = json_decode($resp);
            
            DB::table('esign_log')->insert(['cms_users_id'=>CRUDBooster::myId(),'response'=>$resp]);
            if($response->esign_status==1){
                $pdfpath = 'uploads/' . CRUDBooster::myId() . '/' . date("Y") . '-' . date("m") . '/' . $response->esign_file;
                DB::table('idv_data')->where('id',$idv->id)->update(['signed_pdf'=>$pdfpath ,'status_id'=>5]);
                
                $sukses = DB::table('idv_data')->whereRaw('LENGTH(tag_to_sign) > 0')->where('status_id',5)->count();
                $req = DB::table('idv_data')->whereRaw('LENGTH(tag_to_sign) > 0')->count();
                
                if($req==$sukses){
                    DB::table('dokumen')->where('id',Request::input('id'))->update(['pdf_file'=>$pdfpath, 'status_id' => 5 ,'updated_by'=>CRUDBooster::myId()]);
                }else{
                    DB::table('dokumen')->where('id',Request::input('id'))->update(['pdf_file'=>$pdfpath, 'status_id' => 3 ,'updated_by'=>CRUDBooster::myId()]);
                }
                
                DB::table('bahandap')->where('id',$data['surat']->bahandap_id)->update(['redurl'=>CRUDBooster::adminPath($pdfpath)]);
                CRUDBooster::redirect(CRUDBooster::mainpath('preview-tte/'.Request::input('id').'/'.Request::input('idv_id')),$response->esign_message,"success");
            }else{
                CRUDBooster::redirectBack($response->esign_message, "danger");
            }
        }


	    /*
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate query of index result 
	    | ---------------------------------------------------------------------- 
	    | @query = current sql query 
	    |
	    */
	    public function hook_query_index(&$query) {
	       // $query->whereExists(function ($q) {
        //       $q->select(DB::raw(1))
        //              ->from('idv_data')
        //              ->where('idv_data.parent_table','dokumen')
        //              ->whereColumn('idv_data.parent_id','dokumen.id')
        //              ->where('idv_data.cms_users_id', CRUDBooster::myId());
        //         })->orWhere('dokumen.created_by',CRUDBooster::myId());
        
            $query->where('idv_data.cms_users_id',CRUDBooster::myId());
	    }

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

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | 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) {        
	        //Your code here

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | 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... :) 


	}