<?php namespace App\Http\Controllers;

	use Session;
	use Request;
	use DB;
	use CRUDBooster;
	use Carbon\Carbon;
	use User;
	use Barryvdh\DomPDF\Facade as PDF;
	use \PhpOffice\PhpWord as WORD;
	use File;
	use Illuminate\Support\Facades\Schema;
	use App\QRlib\QRCodeProv;
	use App\Signature\Esign;
	use App\Signature\Client\BasicRest;
	
	use DateTime;

	class AdminSuratIdvController 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 = false;
			$this->button_delete = true;
			$this->button_detail = false;
			$this->button_show = false;
			$this->button_filter = true;
			$this->button_import = false;
			$this->button_export = true;
			$this->table = "surat_idv";
			// $role = DB:table('notasi_surat')->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();

			$this->role = 5;
			# END CONFIGURATION DO NOT REMOVE THIS LINE

			# START COLUMNS DO NOT REMOVE THIS LINE
			$this->col = [];
			$this->col[] = ["label"=>"ID","name"=>"id", "visible" => false];
			$this->col[] = ["label"=>"Parent ID","name"=>"parent_id", "visible" => false];
			$this->col[] = ["label"=>"table","name"=>"parent_table", "visible" => false];
			$this->col[] = ["label"=>"Tanggal","name"=>"tanggal"];
			$this->col[] = ["label"=>"Role","name"=>"status_req","visible"=>false];
			$this->col[] = ["label"=>"Sebagai","name"=>"status_req","join"=>"aksi_diperlukan,keterangan_aksi","visible"=>false];
			$this->col[] = ["label"=>"NIK Pemohon","name"=>"sender_id","join"=>"cms_users,nik","visible"=>false];
			if(CRUDBooster::myPrivilegeId()!=2){
			    $this->col[] = ["label"=>"Nama Pemohon","name"=>"sender_id","join"=>"cms_users,name"];
			}
			$this->col[] = ["label"=>"Perusahaan","name"=>"perusahaan_id","join"=>"perusahaan,nama_perusahaan"];
			$this->col[] = ["label"=>"Alamat Perusahaan","name"=>"perusahaan_id","join"=>"perusahaan,alamat_perusahaan"];
// 			$this->col[] = ["label"=>"Alamat","name"=>"alamat"];
			$this->col[] = ["label"=>"Perihal","name"=>"jenis_surat_id","join"=>"surat,nama_surat"];
// 			$this->col[] = ["label"=>"RT","name"=>"rt"];
// 			$this->col[] = ["label"=>"RW","name"=>"rw"];
            $this->col[] = ["label"=>"Status ID","name"=>"status_id","visible"=>false];
            
            
			
			
			$this->col[] = ["label"=>"Nomor","name"=>"nomor"];
			// $this->col[] = ["label"=>"Nomor SK RT","name"=>"no_sk_rt"];
            if(CRUDBooster::myPrivilegeId()==5){
                $this->col[] = ["label"=>"Penandatangan","name"=>"pejabat_id","join"=>"pejabat,nama_pejabat"];
            }
            if(CRUDBooster::myPrivilegeId()!=2 && CRUDBooster::myPrivilegeId()!=47){
    		    $this->col[] = ["label"=>"Word","name"=>"gen_doc","download"=>"true"];
    		    $this->col[] = ["label"=>"PDF","name"=>"gen_pdf","download"=>"true"];
            }
            if(CRUDBooster::myPrivilegeId()==2 || CRUDBooster::myPrivilegeId()==48){
                $this->col[] = ["label"=>"Signed PDF","name"=>"signed_pdf","download"=>"true"];
            }
			$this->col[] = ["label"=>"Notasi","name"=>"(SELECT aksi_diperlukan_id from notasi_surat WHERE id_cms_privileges = ". CRUDBooster::myPrivilegeId() ." limit 1) as notasiku","callback_php"=>"$row->notasiku", "visible"=>false];
		    $this->col[] = ["label"=>"Status","name"=>"status_id","join"=>"status_surat,status"];
		  //  $this->col[] = ["label"=>"Oleh","name"=>"updated_by","join"=>"cms_users,name"];
			$this->col[] = ["label"=>"Lokasi","name"=>"updated_by_priv","join"=>"cms_privileges,name"];
// 			$this->col[] = ["label"=>"Signed PDF","name"=>"(SELECT signed_pdf from [parent_table] WHERE id = [parent_id] limit 1) as signed","callback_php"=>"$row->signed"];
			// $this->col[] = ["label"=>"PDF Signed","name"=>"signed_pdf","download"=>"true"];

			# END COLUMNS DO NOT REMOVE THIS LINE

			# START FORM DO NOT REMOVE THIS LINE
			$this->form = [];
			$this->form[] = ['label'=>'Jenis Surat','name'=>'jenis_surat_id','type'=>'select2','validation'=>'required|min:1|max:255','width'=>'col-sm-5','datatable'=>'surat,nama_surat','datatable_where'=>'tempat_layanan = "kelurahan"'];
			$this->form[] = ["label"=>"Nomor Surat","name"=>"nomor","type"=>"text","required"=>TRUE,"validation"=>"required|min:1|max:255",'width'=>'col-sm-3'];
			$this->form[] = ["label"=>"Tanggal Surat","name"=>"tanggal","type"=>"date","required"=>TRUE,"validation"=>"required|string|min:5|max:50","value"=>now(),'width'=>'col-sm-3'];
			$this->form[] = ['label'=>'NIK Pemohon','name'=>'sender_id','type'=>'select2','validation'=>'required|min:0|max:255','width'=>'col-sm-6','datatable'=>'warga_bjb,nik','datatable_format'=>'nik," (",nama_lgkp," - ",alamat," )"','datatable_where'=>'nama_kel = '. CRUDBooster::me()->village_id . ' AND EXISTS(SELECT nik FROM cms_users WHERE nik = warga_bjb.nik)'];
			$this->form[] = ['label'=>'Priv Pemohon','name'=>'sender_priv','type'=>'hidden','validation'=>'required|integer|min:0','width'=>'col-sm-3','value'=>2];
			$this->form[] = ['label'=>'Status req','name'=>'status_req','type'=>'hidden','validation'=>'required|integer|min:0','width'=>'col-sm-3','value'=>0];
			
			$this->form[] = ['label'=>'Agama','name'=>'agama','type'=>'select','validation'=>'required|min:1|max:255','width'=>'col-sm-4','dataenum'=>'Islam;Katolik;Protestan;Budha;Hindu'];
			$this->form[] = ['label'=>'Status Perkawinan','name'=>'status_perkawinan','type'=>'select','validation'=>'required|min:1|max:255','width'=>'col-sm-4','dataenum'=>'Lajang;Menikah;Janda;Duda'];
			
			$this->form[] = ["label"=>"Tanggal SK RT","name"=>"tgl_sk_rt","type"=>"date","required"=>TRUE,"validation"=>"required|string|min:5|max:5000","value"=>now(),'width'=>'col-sm-3'];
			$this->form[] = ["label"=>"Nomor SK RT","name"=>"no_sk_rt","type"=>"text","required"=>TRUE,"validation"=>"required|min:1|max:255",'width'=>'col-sm-3'];
			$this->form[] = ["label"=>"File SK RT","name"=>"file_sk_rt","type"=>"upload","validation"=>"min:1|max:255",'width'=>'col-sm-4'];
			
			$this->form[] = ['label'=>'Keterangan Khusus','name'=>'keterangan','type'=>'textarea','validation'=>'string|min:5|max:5000','width'=>'col-sm-5'];
			$this->form[] = ['label'=>'Keperluan','name'=>'keperluan','type'=>'textarea','validation'=>'required|string|min:5|max:5000','width'=>'col-sm-5'];
			
			$this->form[] = ['label'=>'Penandatangan','name'=>'pejabat_id','type'=>'select2','validation'=>'required|integer|min:0|max:255','width'=>'col-sm-8','datatable'=>'pejabat,nip_pejabat','datatable_format'=>'nip_pejabat," (",nama_pejabat," - ",(SELECT jabatan FROM jabatan WHERE id = pejabat.jabatan_id)," )"','datatable_where'=>'dinas_id = '. Session::get('dinas_id')];
			
			$this->form[] = ['label'=>'Tag To Sign','name'=>'tag_to_sign','type'=>'hidden','validation'=>'required|string|min:0','width'=>'col-sm-3','value'=>"#"];
			$this->form[] = ['label'=>'Status Surat','name'=>'status_id','type'=>'hidden','validation'=>'required|integer|min:0','width'=>'col-sm-3','value'=>1];
			$this->form[] = ['label'=>'Updated By','name'=>'updated_by','type'=>'hidden','validation'=>'required|integer|min:0','width'=>'col-sm-3','value'=>CRUDBooster::myId()];
			$this->form[] = ['label'=>'Updated By Priv','name'=>'cms_privilege_id','type'=>'hidden','validation'=>'required|integer|min:0','width'=>'col-sm-3','value'=>CRUDBooster::myPrivilegeId()];
			# 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"=>"Cms Privilege Id","name"=>"cms_privilege_id","type"=>"select2","required"=>TRUE,"validation"=>"required|integer|min:0","datatable"=>"cms_privilege,id"];
			//$this->form[] = ["label"=>"Status Req","name"=>"status_req","type"=>"number","required"=>TRUE,"validation"=>"required|integer|min:0"];
			//$this->form[] = ["label"=>"Status Id","name"=>"status_id","type"=>"select2","required"=>TRUE,"validation"=>"required|integer|min:0","datatable"=>"status,id"];
			//$this->form[] = ["label"=>"Tag To Sign","name"=>"tag_to_sign","type"=>"text","required"=>TRUE,"validation"=>"required|min:1|max:255"];
			//$this->form[] = ["label"=>"Signed Pdf","name"=>"signed_pdf","type"=>"textarea","required"=>TRUE,"validation"=>"required|string|min:5|max:5000"];
			# 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'=>'Daftar Pekerja','path'=>'perjanjian_kerja_waktu_tertentu_child','foreign_key'=>'[id]','button_color'=>'danger','parent_columns'=>'nomor','showIf'=>"[parent_table]=='perjanjian_kerja_waktu_tertentu'"];


	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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();
	        if(CRUDBooster::myPrivilegeId()!=2) { //Admin dinkop
				$this->addaction[] = ['label'=>'Periksa','icon'=>'fa fa-eye','color'=>'warning','url'=>CRUDBooster::mainpath('lihat-surat').'/[id]', "showIf"=>'[notasiku] <= 4'];//,'showIf'=>'[status_id] == 1 OR [status_id] == 5 OR [status_id] == 4 OR [status_by] > ' . CRUDBooster::myPrivilegeId()];
			    // $this->addaction[] = ['label'=>'Create PDF','icon'=>'fa fa-chat','color'=>'danger','url'=>CRUDBooster::mainpath('re-pdf').'/[id]','showIf'=>'[gen_pdf]=="" && [gen_doc]!=""'];
	            $this->addaction[] = ['label'=>'Perbarui','color'=>'default','url'=>CRUDBooster::mainpath('cetak-surat').'/[id]/1/true','showIf'=>'[notasiku]==3 && [gen_doc]!=""'];
	        }
			$this->addaction[] = ['label'=>'Periksa','icon'=>'fa fa-eye','color'=>'warning','url'=>CRUDBooster::mainpath('lihat-pdf/[id]').'?next_url='. CRUDBooster::adminPath('[parent_table]/edit/[parent_id]'), "showIf"=>'[notasiku] == 5'];
            // $this->addaction[] = ['label'=>'Periksa','icon'=>'fa fa-eye','color'=>'warning','url'=>CRUDBooster::adminPath('[parent_table]/edit').'/[id]', "showIf"=>'[notasiku] == 5'];
            $this->addaction[] = ['label'=>'Diskusi','icon'=>'fa fa-chat','color'=>'info','url'=>CRUDBooster::mainpath('diskusi').'/[id]'];
            
            if(CRUDBooster::myPrivilegeId()==2) {
                $this->addaction[] = ['label'=>'Edit','icon'=>'fa fa-pencil','color'=>'danger','url'=>CRUDBooster::adminPath('[parent_table]/edit').'/[parent_id]?return_url='.CRUDBooster::mainpath(), "showIf"=>"[status_id]==4"];
            }
            
            if(CRUDBooster::myPrivilegeId()==48) {
                $this->addaction[] = [
                        'label'=>'Daftar Pekerja',
                        'icon'=>'fa fa-list',
                        'color'=>'danger',
                        'url'=>CRUDBooster::adminPath('[parent_table]_child').'?return_url='.CRUDBooster::mainpath().'&parent_table=perjanjian_kerja_waktu_tertentu&parent_columns=pemohon,nama_perusahaan,nomor,peruntukan&parent_columns_alias=&parent_id=[parent_id]&foreign_key=parent_id&label=Daftar Pekerja',
                        "showIf"=>"[parent_table]=='perjanjian_kerja_waktu_tertentu'"
                    ];
                $this->addaction[] = ['label'=>'Catatan','icon'=>'fa fa-note','color'=>'success','url'=>CRUDBooster::adminPath('[parent_table]/edit').'/[parent_id]?command=catatan&return_url='.CRUDBooster::mainpath(),"showIf"=>"[parent_table]=='perjanjian_kerja_waktu_tertentu'"];
                // $this->addaction[] = ['label'=>'Teruskan','icon'=>'fa fa-arrow-right','color'=>'info','url'=>CRUDBooster::adminPath('[parent_table]/edit').'/[parent_id]?command=teruskan&return_url='.CRUDBooster::mainpath(),"showIf"=>"[gen_doc]<>''"];
                $this->addaction[] = ['label'=>'Teruskan','icon'=>'fa fa-arrow-right','color'=>'info','url'=>CRUDBooster::adminPath('[parent_table]/teruskan').'/[parent_id]/[id]?return_url='.CRUDBooster::mainpath(),"showIf"=>"[gen_pdf]<>''"];
                $this->addaction[] = ['label'=>'Upload SK','icon'=>'fa fa-upload','color'=>'success','url'=>CRUDBooster::mainpath("upload-tte/[id]?return_url=".CRUDBooster::adminPath('surat_idv'))];
            }
	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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','icon'=>'fa fa-check','name'=>'tandatangani'];

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



	        /* 
	        | ---------------------------------------------------------------------- 
	        | 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] == 2','color'=>'primary'];
	        $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();
			 //admin naker
			 if(CRUDBooster::myPrivilegeId()>=46 && CRUDBooster::myPrivilegeId()<=48){
    	        $this->index_statistic[] = ['label'=>'Baru','count'=>DB::table($this->table)->where('status_id',1)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-envelope','color'=>'red','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Diproses','count'=>DB::table($this->table)->where('status_id','>',1)
    																									 ->where('status_id','<',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-inbox','color'=>'green','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Selesai','count'=>DB::table($this->table)->where('status_id',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-check','color'=>'blue','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Semua','count'=>DB::table($this->table)->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-bars','color'=>'yellow','width'=>'col-sm-3'];
	        }

	        //admin kelurahan
	        if(CRUDBooster::myPrivilegeId()==5){
    	        $this->index_statistic[] = ['label'=>'Baru','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('village_id',CRUDBooster::me()->village_id)
        																									 ->where('status_id',1)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-envelope','color'=>'red','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Diproses','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('village_id',CRUDBooster::me()->village_id)
    																									 ->where('status_id','>',1)
    																									 ->where('status_id','<',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-inbox','color'=>'green','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Selesai','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('village_id',CRUDBooster::me()->village_id)
    																									 ->where('status_id',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-check','color'=>'blue','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Semua','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('village_id',CRUDBooster::me()->village_id)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-bars','color'=>'yellow','width'=>'col-sm-3'];
	        }
	        
	        //ketua RT
	        if(CRUDBooster::myPrivilegeId()==3){
    	        $this->index_statistic[] = ['label'=>'Baru','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('surat_idv.village_id',Session::get('admin_village'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rt AS UNSIGNED) = '.Session::get('admin_rt'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
        																									 ->where('status_id',1)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-envelope','color'=>'red','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Diproses','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('surat_idv.village_id',Session::get('admin_village'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rt AS UNSIGNED) = '.Session::get('admin_rt'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
    																									 ->where('status_id','>',1)
    																									 ->where('status_id','<',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-inbox','color'=>'green','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Selesai','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('surat_idv.village_id',Session::get('admin_village'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rt AS UNSIGNED) = '.Session::get('admin_rt'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
    																									 ->where('status_id',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeID())
    																									 ->count(),'icon'=>'fa fa-check','color'=>'blue','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Semua','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('surat_idv.village_id',Session::get('admin_village'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rt AS UNSIGNED) = '.Session::get('admin_rt'))
                                                                                        	                ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-bars','color'=>'yellow','width'=>'col-sm-3'];
	        }
	        
	        //Ketua RW
	        if(CRUDBooster::myPrivilegeId()==4){
    	        $this->index_statistic[] = ['label'=>'Baru','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('village_id',CRUDBooster::me()->village_id)
        																									 ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
        																									 ->where('status_id',1)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-envelope','color'=>'red','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Diproses','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('village_id',CRUDBooster::me()->village_id)
    																									 ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
    																									 ->where('status_id','>',1)
    																									 ->where('status_id','<',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-inbox','color'=>'green','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Selesai','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('village_id',CRUDBooster::me()->village_id)
    																									 ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
    																									 ->where('status_id',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeID())
    																									 ->count(),'icon'=>'fa fa-check','color'=>'blue','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Semua','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('village_id',CRUDBooster::me()->village_id)
        																									 ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-bars','color'=>'yellow','width'=>'col-sm-3'];
	        }
	        
	        //lurah
	        if(CRUDBooster::myPrivilegeId()==6){
    	        $this->index_statistic[] = ['label'=>'Baru','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('village_id',CRUDBooster::me()->village_id)
        																									 ->where('status_id',1)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-envelope','color'=>'red','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Diproses','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('village_id',CRUDBooster::me()->village_id)
    																									 ->where('status_id','>',1)
    																									 ->where('status_id','<',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-inbox','color'=>'green','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Selesai','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('village_id',CRUDBooster::me()->village_id)
    																									 ->where('status_id',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeID())
    																									 ->count(),'icon'=>'fa fa-check','color'=>'blue','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Pending','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('village_id',CRUDBooster::me()->village_id)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																								     ->where('status_id',7)
        																									 ->count(),'icon'=>'fa fa-bars','color'=>'yellow','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Semua','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('village_id',CRUDBooster::me()->village_id)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-bars','color'=>'yellow','width'=>'col-sm-3'];
	        }
	        
	        //lurah
	        if(CRUDBooster::myPrivilegeId()==8){
    	        $this->index_statistic[] = ['label'=>'Baru','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('status_id',1)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-envelope','color'=>'red','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Diproses','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('status_id','>',1)
    																									 ->where('status_id','<',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    																									 ->count(),'icon'=>'fa fa-inbox','color'=>'green','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Selesai','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('district_id',CRUDBooster::me()->district_id)
    																									 ->where('status_id',5)
    																									 ->where('cms_privilege_id', CRUDBooster::myPrivilegeID())
    																									 ->count(),'icon'=>'fa fa-check','color'=>'blue','width'=>'col-sm-3'];
    			$this->index_statistic[] = ['label'=>'Semua','count'=>DB::table($this->table)->where('district_id',CRUDBooster::me()->district_id)
        																									 ->where('district_id',CRUDBooster::me()->district_id)
        																								     ->where('cms_privilege_id',  CRUDBooster::myPrivilegeId())
        																									 ->count(),'icon'=>'fa fa-bars','color'=>'yellow','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) {
	        //Your code here
	            
	    }


	    /*
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate query of index result 
	    | ---------------------------------------------------------------------- 
	    | @query = current sql query 
	    |
	    */
	    public function hook_query_index(&$query) {
	        //dd(ini_get('allow_url_fopen'));
	        //ketua RT
	        if(CRUDBooster::myPrivilegeId()==3){
    	        $query->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('surat_idv.village_id',Session::get('admin_village'))
    	                ->whereRaw('CAST(surat_idv.rt AS UNSIGNED) = '.Session::get('admin_rt'))
    	                ->whereRaw('CAST(surat_idv.rw AS UNSIGNED) = '.Session::get('admin_rw'))
    	                ->where('status_id','>',0);
	        }
	        
	        //ketua RW
	        if(CRUDBooster::myPrivilegeId()==4){
	            $query->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('surat_idv.village_id',Session::get('admin_village'))
    	                ->where('surat_idv.rw',Session::get('admin_rw'))
    	                ->where('status_id','>',0);
	        }
	        
	        //Admin Kelurahan
	        if(CRUDBooster::myPrivilegeId()==5){
	            $query->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('surat_idv.village_id',Session::get('admin_village'))
    	                ->where('status_id','>',0);
	        }
	        
	        
	        //lurah
	        if(CRUDBooster::myPrivilegeId()==6){
    	        $query->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('surat_idv.village_id',Session::get('admin_village'))
    	                ->where('status_id','>',0);
	        }
	        
	        //camat
	        if(CRUDBooster::myPrivilegeId()==8){
    	        $query->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('surat_idv.district_id',Session::get('admin_district'))
    	                ->where('status_id','>',0);
	        }

			//admin naker
	        if(CRUDBooster::myPrivilegeId()>=46 && CRUDBooster::myPrivilegeId()<=47){
    	        $query->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('status_id','>',0);
	        }
	        
	        //Mediator
	        if(CRUDBooster::myPrivilegeId()==48){
    	        $query->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('target_id', CRUDBooster::myId())
    	                ->where('status_id','>',0);
	        }
	        
	        //Warga
	        if(CRUDBooster::myPrivilegeId()==2){
	            $query->where('sender_id', CRUDBooster::myId())
	                    ->where('cms_privilege_id', CRUDBooster::myPrivilegeId())
    	                ->where('status_id','>',0);
	        }
	    }

	    /*
	    | ---------------------------------------------------------------------- 
	    | 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) {
	       // dd($postdata);
	        $jenis_surat = DB::table('surat')->where('id',$postdata['jenis_surat_id'])->first();
	        $postdata['parent_table'] = $jenis_surat->tabel;
	        $kepedudukan_pemohon = DB::table('warga_bjb')->where('id',$postdata['sender_id'])->first();
	        $cms_user_pemohon = DB::table('cms_users')->where('nik',$kepedudukan_pemohon->nik)->first();
	        $pejabat = DB::table('pejabat')->where('id',$postdata['pejabat_id'])->first();
	        $postdata['sender_id'] = $cms_user_pemohon->id;
	        $postdata['nik'] = $kepedudukan_pemohon->nik;
	        $postdata['nomor'] = strtoupper($postdata['nomor']);
	        $postdata['no_sk_rt'] = strtoupper($postdata['no_sk_rt']);
	        
	        $exist = DB::table($jenis_surat->tabel)->where('nomor',$postdata['nomor'])->first();
	        
	        if(!$exist){
    	        $parent = DB::table($postdata['parent_table'])->insertGetId([
    	                "tanggal" => $postdata['tanggal'],
    	                "nomor" => $postdata['nomor'],
    	                "cms_user_id" => $cms_user_pemohon->id,
    	                "warga_bjb_id" => $kepedudukan_pemohon->id,
    	                "agama" => $postdata['agama'],
    	                "keperluan" => $postdata['keperluan'],
    	                "keterangan" => $postdata['keterangan'],
    	                "no_sk_rt" => $postdata['no_sk_rt'],
    	                "tgl_sk_rt" => $postdata['tgl_sk_rt'],
    	                "status_perkawinan" => $postdata['status_perkawinan'],
    	                "created_at" => $postdata['tanggal'],
    	                "pejabat_id" => $postdata['pejabat_id'],
    	                "status_id" => 3,
    	                "updated_by" => CRUDBooster::myId(),
    	            ]);
    	            
    	         $postdata['parent_id'] = $parent;
    	         $postdata['nama_lgkp'] = $kepedudukan_pemohon->nama_lgkp;
    	         $postdata['tmpt_lhr'] = $kepedudukan_pemohon->tmpt_lhr;
    	         $postdata['tgl_lhr'] = $kepedudukan_pemohon->tgl_lhr;
    	         $postdata['alamat'] = $kepedudukan_pemohon->alamat2;
    	         $postdata['status_perkawinan'] = $postdata['status_perkawinan'];
    	         $postdata['agama'] = $postdata['agama'];
    	         $postdata['rt'] = $kepedudukan_pemohon->rt;
    	         $postdata['rw'] = $kepedudukan_pemohon->rw;
    	         $postdata['village_id'] = $kepedudukan_pemohon->nama_kel;
    	         $postdata['district_id'] = $kepedudukan_pemohon->nama_kec;
    	         $postdata['regency_id'] = $kepedudukan_pemohon->nama_kab;
    	         $postdata['province_id'] = $kepedudukan_pemohon->nama_prop;
    	         $postdata['jk'] = $kepedudukan_pemohon->jk;
    	         $postdata['pekerjaan'] = $kepedudukan_pemohon->pekerjaan;
    	         $postdata['no_telp'] = $cms_user_pemohon->no_telp;
    	         
    	         $notasiku = DB::table('notasi_surat')->where('id_surat',$postdata['jenis_surat_id'])->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
    	         
    	         
    	         
    	         $postdata['status_req'] = $notasiku->aksi_diperlukan_id;
    	         
    	         $notasiprev = DB::table('notasi_surat')->where('id_surat',$postdata['jenis_surat_id'])->where('urutan','<',$notasiku->urutan)->get();
    	         //dd($notasiprev);
    	        foreach($notasiprev as $np){
    	           DB::table('surat_idv')->insert([
                                    'parent_table' => $jenis_surat->tabel,
                                    'parent_id' => $parent,
                                    'cms_privilege_id' => $np->id_cms_privileges,
                                    'status_req' => $np->aksi_diperlukan_id,
                                    'status_id' => 3,
                                	'jenis_surat_id' => $postdata['jenis_surat_id'],
                                	 "nomor" => strtoupper($postdata['nomor']),
                                	 "tanggal" => $postdata['tanggal'],
                					'sender_id' => $cms_user_pemohon->id,
                					'sender_priv' => 2,
                					'nik' => $kepedudukan_pemohon->nik,
                					'nama_lgkp' => $kepedudukan_pemohon->nama_lgkp,
                					'tmpt_lhr' => $kepedudukan_pemohon->tmpt_lhr,
                					'tgl_lhr' => $kepedudukan_pemohon->tgl_lhr,
                					'alamat' => $kepedudukan_pemohon->alamat2,
                					"no_sk_rt" => $postdata['no_sk_rt'],
    	                            "tgl_sk_rt" => $postdata['tgl_sk_rt'],
                					'agama' => $postdata['agama'],
                					'status_perkawinan' => $postdata['status_perkawinan'],
                					'rt' => $kepedudukan_pemohon->rt,
                					'rw' => $kepedudukan_pemohon->rw,
                					'village_id' => $kepedudukan_pemohon->nama_kel,
                					'district_id' => $kepedudukan_pemohon->nama_kec,
                					'regency_id' => $kepedudukan_pemohon->nama_kab,
                					'province_id' => $kepedudukan_pemohon->nama_prop,
                					'jk' => $kepedudukan_pemohon->jk,
                					'pekerjaan' => $kepedudukan_pemohon->pekerjaan,
                					'no_telp' => $cms_user_pemohon->no_telp,
                					'keperluan' => $postdata['keperluan'],
                					"pejabat_id" => $postdata['pejabat_id'],
                					'next_priv' => $np->privilege_tujuan,
                					'created_at' =>  $postdata['tanggal'],
                					"updated_by" => CRUDBooster::myId()
                                ]); 
    	        }
	        
	        }else{
	            CRUDBooster::redirectBack('Nomor surat '. $postdata['nomor'] .' sudah ada, harap ganti nomor surat !','danger');
	        }

	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command after add public static function called 
	    | ---------------------------------------------------------------------- 
	    | @id = last insert id
	    | 
	    */
	    public function hook_after_add($id) {        
	        //Your code here
	        
            $this->postCetakSuratDua($id,false);
	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for manipulate data input before update data is execute
	    | ---------------------------------------------------------------------- 
	    | @postdata = input post data 
	    | @id       = current id 
	    | 
	    */
	    public function hook_before_edit(&$postdata,$id) {        
	        $surat = DB::table('surat_idv')->where('id',$id)->first();
            if($surat->status_id == 5){
                CRUDBooster::redirectBack('Permohonan yang sudah di tandatangani tidak bisa diubah !','danger');
            }else{
                $jenis_surat = DB::table('surat')->where('id',$postdata['jenis_surat_id'])->first();
    	        $postdata['parent_table'] = $jenis_surat->tabel;
    	        $kepedudukan_pemohon = DB::table('warga_bjb')->where('id',$postdata['sender_id'])->first();
    	        $cms_user_pemohon = DB::table('cms_users')->where('nik',$kepedudukan_pemohon->nik)->first();
    	        $postdata['sender_id'] = $cms_user_pemohon->id;
    	        $postdata['nik'] = $kepedudukan_pemohon->nik;
    	        $postdata['nomor'] = strtoupper($postdata['nomor']);
	            $postdata['no_sk_rt'] = strtoupper($postdata['no_sk_rt']);
    	        
    	        DB::table($postdata['parent_table'])->where('id',$surat->parent_id)
    	            ->update([
    	                "tanggal" => $postdata['tanggal'],
    	                "nomor" => $postdata['nomor'],
    	                "cms_user_id" => $cms_user_pemohon->id,
    	                "warga_bjb_id" => $kepedudukan_pemohon->id,
    	                "agama" => $postdata['agama'],
    	                "keperluan" => $postdata['keperluan'],
    	                "keterangan" => $postdata['keterangan'],
    	                "no_sk_rt" => $postdata['no_sk_rt'],
    	                "tgl_sk_rt" => $postdata['tgl_sk_rt'],
    	                "status_perkawinan" => $postdata['status_perkawinan'],
    	                "created_at" => $postdata['tanggal'],
    	                "pejabat_id" => $postdata['pejabat_id'],
    	                "status_id" => 3,
    	                "updated_by" => CRUDBooster::myId(),
    	            ]);
    	            
    	         $postdata['parent_id'] = $surat->parent_id;
    	         $postdata['nama_lgkp'] = $kepedudukan_pemohon->nama_lgkp;
    	         $postdata['tmpt_lhr'] = $kepedudukan_pemohon->tmpt_lhr;
    	         $postdata['tgl_lhr'] = $kepedudukan_pemohon->tgl_lhr;
    	         $postdata['alamat'] = $kepedudukan_pemohon->alamat2;
    	         $postdata['status_perkawinan'] = $postdata['status_perkawinan'];
    	         $postdata['agama'] = $postdata['agama'];
    	         $postdata['rt'] = $kepedudukan_pemohon->rt;
    	         $postdata['rw'] = $kepedudukan_pemohon->rw;
    	         $postdata['village_id'] = $kepedudukan_pemohon->nama_kel;
    	         $postdata['district_id'] = $kepedudukan_pemohon->nama_kec;
    	         $postdata['regency_id'] = $kepedudukan_pemohon->nama_kab;
    	         $postdata['province_id'] = $kepedudukan_pemohon->nama_prop;
    	         $postdata['jk'] = $kepedudukan_pemohon->jk;
    	         $postdata['pekerjaan'] = $kepedudukan_pemohon->pekerjaan;
    	         $postdata['no_telp'] = $cms_user_pemohon->no_telp;
    	         
    	         $notasiku = DB::table('notasi_surat')->where('id_surat',$postdata['jenis_surat_id'])->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
    	         
    	         
    	         
    	         $postdata['status_req'] = $notasiku->aksi_diperlukan_id;
    	         
    	        // $notasiprev = DB::table('notasi_surat')->where('id_surat',$postdata['jenis_surat_id'])->where('urutan','<',$notasiku->urutan)->get();
    	         //dd($notasiprev);
    	 
    	           DB::table('surat_idv')
    	                ->where('parent_table',$surat->parent_table)
    	                ->where('parent_id',$surat->id)
    	                ->update([  'jenis_surat_id' => $postdata['jenis_surat_id'],
                                	 "nomor" => $postdata['nomor'],
                                	 "tanggal" => $postdata['tanggal'],
                					'sender_id' => $cms_user_pemohon->id,
                					'sender_priv' => 2,
                					'nik' => $kepedudukan_pemohon->nik,
                					'nama_lgkp' => $kepedudukan_pemohon->nama_lgkp,
                					'tmpt_lhr' => $kepedudukan_pemohon->tmpt_lhr,
                					'tgl_lhr' => $kepedudukan_pemohon->tgl_lhr,
                					'alamat' => $kepedudukan_pemohon->alamat2,
                					"no_sk_rt" => $postdata['no_sk_rt'],
    	                            "tgl_sk_rt" => $postdata['tgl_sk_rt'],
                					'agama' => $postdata['agama'],
                					'status_perkawinan' => $postdata['status_perkawinan'],
                					'rt' => $kepedudukan_pemohon->rt,
                					'rw' => $kepedudukan_pemohon->rw,
                					'village_id' => $kepedudukan_pemohon->nama_kel,
                					'district_id' => $kepedudukan_pemohon->nama_kec,
                					'regency_id' => $kepedudukan_pemohon->nama_kab,
                					'province_id' => $kepedudukan_pemohon->nama_prop,
                					'jk' => $kepedudukan_pemohon->jk,
                					'pekerjaan' => $kepedudukan_pemohon->pekerjaan,
                					'no_telp' => $cms_user_pemohon->no_telp,
                					'keperluan' => $postdata['keperluan'],
                					"pejabat_id" => $postdata['pejabat_id'],
                					"updated_by" => CRUDBooster::myId()
                                ]); 
    	      
    	        
    	        //delete file
    	        
            }
	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command after edit public static function called
	    | ----------------------------------------------------------------------     
	    | @id       = current id 
	    | 
	    */
	    public function hook_after_edit($id) {
	       // $this->postCetakSuratDua($id,false,1);
	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command before delete public static function called
	    | ----------------------------------------------------------------------     
	    | @id       = current id 
	    | 
	    */
	    public function hook_before_delete($id) {
	        //Your code here
            $surat = DB::table('surat_idv')->where('id',$id)->first();
            if($surat->status_id >= 5){
                CRUDBooster::redirectBack('Permohonan yang sudah di tandatangani tidak bisa dihapus !','danger');
            }else{
                DB::table('surat_idv')
	                ->where('parent_id',$surat->parent_id)
	                ->where('parent_table',$surat->parent_table)
	                ->where('status_id','<>', 5)
	                ->delete();
	                
    	        DB::table($surat->parent_table)
    	                ->where('id',$surat->parent_id)
    	                ->where('status_id','<', 5)
    	                ->delete();
            }
            
	    }

	    /* 
	    | ---------------------------------------------------------------------- 
	    | Hook for execute command after delete public static function called
	    | ----------------------------------------------------------------------     
	    | @id       = current id 
	    | 
	    */
	    public function hook_after_delete($id) {
	        
	    }
	    
	    public function getLihatSurat($id){
		    $data = [];
		    $data['surat'] = DB::table('surat_idv')->where('id',$id)->first();
			
		    $data['pemohon'] = DB::table('cms_users')->where('id',$data['surat']->sender_id)->first();
		    $data['parent'] = DB::table($data['surat']->parent_table)->where('id',$data['surat']->parent_id)->first();
		    $data['batal'] = "surat_idv"; 

		    if($data['parent']->nomor){
		        $data['nomor'] = '';
		    }
		    
		    $data['admrole'] = DB::table('notasi_surat')
		                            ->join('aksi_diperlukan','aksi_diperlukan.id','notasi_surat.aksi_diperlukan_id')
		                            ->where('notasi_surat.id', $data['surat']->jenis_surat_id)
		                            ->first();
		    
		    
		    $data['warga'] = DB::table('warga_bjb')
            		        ->join('districts','warga_bjb.nama_kec','=','districts.id')
            				->join('villages','warga_bjb.nama_kel','=','villages.id')
            				->where('warga_bjb.nik',$data['pemohon']->nik)
            				->select('warga_bjb.*','villages.name as kelurahan','districts.name as  kecamatan')
		                    ->first();

		    $data['id'] = $id;
		    $data['rel_table'] = $data['surat']->parent_table;
		    $data['rel_id'] = $data['surat']->parent_id;
		    
		    
		    
		    
		    $data['pejabat'] = DB::table('pejabat')->where('dinas_id',CRUDBooster::me()->dinas_id)->get();
		    
		    $data['jenis_surat'] = DB::table('surat')->where('id',$data['surat']->jenis_surat_id)->first();
		    $data['notasi_surat'] = DB::table('notasi_surat')->where('id_surat',$data['jenis_surat']->id)->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
		    $data['notasi_next'] = DB::table('notasi_surat')->where('id_surat',$data['jenis_surat']->id)->where('urutan',$data['notasi_surat']->urutan+1)->first();
		    
		    $data['layanan'] = DB::table('layanan')
						->where('jenis_surat_id',$data['surat']->jenis_surat_id)
						->where('village_id',CRUDBooster::me()->village_id)
						->first();
						
 		    if( $data['surat']->status_id < 5){
    		    // DB::table('surat_idv')
        		//   ->where('id',$id)
        		//   ->update(['status_id'=>2]);
				DB::table('surat_idv')
						->where('jenis_surat_id',$data['surat']->jenis_surat_id)
						->where('parent_id',$data['surat']->parent_id)
						->where('id','<=',$id)
						->update(['status_id'=>2,'updated_by'=>CRUDBooster::myId(),'updated_by_priv' => CRUDBooster::myPrivilegeId()]);
 		    }
    		  

		    
		    // $this->cbView( $data['notasi_surat']->view,$data);
			return redirect(CRUDBooster::adminPath($data['rel_table']."/detail/".$data['rel_id']."?return_url=".CRUDBooster::adminPath('surat_idv')."&next_action=".CRUDBooster::adminPath("surat_idv/teruskan/".$id."&surat_idv_id=".$id)));
		}

		public function getLihatPdf($id){
			$data = [];
			$data['id'] = $id;
		    $data['surat'] = DB::table('surat_idv')->where('id',$id)->first();
			
		    $data['pemohon'] = DB::table('cms_users')->where('id',$data['surat']->sender_id)->first();
		    $data['parent'] = DB::table($data['surat']->parent_table)->where('id',$data['surat']->parent_id)->first();
		  //  dd($data['parent']);
		    if( $data['surat']->status_id < 5){

				DB::table('surat_idv')
						->where('jenis_surat_id',$data['surat']->jenis_surat_id)
						->where('parent_id',$data['surat']->parent_id)
						->where('id','<=',$id)
						->update(['status_id'=>2,'updated_by'=>CRUDBooster::myId(),'updated_by_priv' => CRUDBooster::myPrivilegeId()]);
 		    }
		    
		  //  dd($data);

			$this->cbView('surat.form.preview',$data);
		}
		
		public function getDiskusi($id){
		    $data = [];
		    $data['surat'] = DB::table('surat_idv')->where('id',$id)->first();
		    $data['pemohon'] = DB::table('cms_users')->where('id',$data['surat']->sender_id)->first();
		    $data['parent'] = DB::table($data['surat']->parent_table)->where('id',$data['surat']->parent_id)->first();
		    $data['jenis'] = DB::table('surat')->where('id',$data['surat']->jenis_surat_id)->first();

		    $data['id'] = $id;
		    $data['rel_table'] = $data['surat']->parent_table;
		    $data['rel_id'] = $data['surat']->parent_id;
            
            
		    
		    $this->cbView( 'surat.form.tolak',$data);
		}
		
		public function postDiskusi(){
		    $surat_idv = DB::table('surat_idv')->where('id', Request::input('id'))->first();
		    $permohonan = DB::table($surat_idv->parent_table)->where('id', $surat_idv->parent_id)->first();
		    $jenis_surat = DB::table('surat')->where('id',$surat->jenis_surat_id)->first();
		    DB::table('surat_idv')
		            ->where('jenis_surat_id',Request::input('jenis_surat_id'))
		            ->where('parent_id',Request::input('rel_id'))
		            ->where('parent_table',Request::input('rel_table'))
		            ->update(['diskusi'=> CRUDBooster::myName() ."(" . Session::get('admin_privileges_name') .") - " . now() . " : \n" .  Request::input('diskusi') . "\n\n" . $surat_idv->diskusi]);
		            
		    CRUDBooster::sendNotifikasi($permohonan->created_by,2,CRUDBooster::myPrivilegeName() . ' Mengimkan pesan pada permohonan ' . $jenis_surat->nama_surat,CRUDBooster::adminPath('surat_idv/diskusi/'.Request::input('id')));
            CRUDBooster::sendNotifikasi(0,46,CRUDBooster::myPrivilegeName() . ' Mengimkan pesan pada permohonan ' . $jenis_surat->nama_surat,CRUDBooster::adminPath('surat_idv/diskusi/'.Request::input('id')));
		    
		    return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv/diskusi/'.Request::input('id')),'Diskusi sudah berhasil dikirim.','success');
		}   
		
		public function getTolak($id){
		    $surat_idv = DB::table('surat_idv')->where('id', $id)->first();
		    $permohonan = DB::table($surat_idv->parent_table)->where('id', $surat_idv->parent_id)->first();
		    $jenis_surat = DB::table('surat')->where('id',$surat->jenis_surat_id)->first();
		    DB::table('surat_idv')
		            ->where('jenis_surat_id',$surat_idv->jenis_surat_id)
		            ->where('parent_id',$surat_idv->parent_id)
		            ->where('parent_table',$surat_idv->parent_table)
		            ->update(['diskusi'=> CRUDBooster::myName() ."(" . Session::get('admin_privileges_name') .") - " . now() . " : \n MENOLAK \n\n" . $surat_idv->diskusi,'status_id'=> 4, "updated_by" => CRUDBooster::myId()]);
		    
		    DB::table($surat_idv->parent_table)
		            ->where('id',$surat_idv->parent_id)
		            ->update(['status_id'=> 4, "updated_by" => CRUDBooster::myId()]);
		            
		    CRUDBooster::sendNotifikasi($permohonan->created_by,2,CRUDBooster::myPrivilegeName() . ' Menolak permohonan ' . $jenis_surat->nama_surat,CRUDBooster::adminPath('surat_idv'));
		    
		    return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan telah ditolak.','warning');
		} 
		
		public function getTeruskan($id,$role){
		    $data = [];
		    $data['surat'] = DB::table('surat_idv')->where('id',$id)->first();
		    $data['parent'] = DB::table($data['surat']->parent_table)->where('id',$data['surat']->parent_id)->first();
		    $data['jenis_surat'] = DB::table('surat')->where('id',$data['surat']->jenis_surat_id)->first();
		    $data['perusahaan'] = DB::table('perusahaan')->where('id',$data['parent']->perusahaan_id)->first();
		    $data['modul'] = DB::table('cms_moduls')->where('id',$data['jenis_surat']->model)->first();
		    $data['pejabat'] = DB::table('pejabat')
		                        ->join('jabatan','pejabat.jabatan_id','jabatan.id')
		                        ->where('pejabat.dinas_id',CRUDBooster::me()->dinas_id)
		                        ->selectRaw('pejabat.*, jabatan.jabatan')
		                        ->get();
		                        
		  
		                        
		    
		    $data['terkirim'] = DB::table('surat_idv')->where('parent_table',$data['surat']->parent_table)->where('parent_id',$data['surat']->parent_id)->where('id','>',$id)->first();
		    
			

			if($role == 3){
			 //   return redirect(CRUDBooster::adminPath($data['rel_table']."/edit/".$data['rel_id']."?return_url=".CRUDBooster::adminPath('surat_idv')."&next_action=".CRUDBooster::adminPath("surat_idv/teruskan/".$id."&surat_idv_id=".$id)));
				$this->cbView('surat.form.nomor',$data);
			}elseif($role == 4){
			    $data['mediator'] = DB::table('multi_privs')
		                        ->join('cms_users','cms_users.id','multi_privs.cms_users_id')
		                        ->where('multi_privs.cms_privileges_id',48)
		                        ->selectRaw('cms_users.*')
		                        ->get();
		      // dd($data['mediator']);
			    $this->cbView('surat.form.select_mediator',$data);
				// $this->teruskanSaja($id);
			}elseif($role == 5){
                
			}
    
		}

		private function teruskanSaja($id){
			$surat = DB::table('surat_idv')->where('id',$id)->first();
		    $parent = DB::table($surat->parent_table)->where('id',$surat->parent_id)->first();
		    $jenis_surat = DB::table('surat')->where('id',$surat->jenis_surat_id)->first();
		    $notasiku = DB::table('notasi_surat')->where('id_surat',$surat->jenis_surat_id)->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
    		$notasinext = DB::table('notasi_surat')->where('id_surat',$surat->jenis_surat_id)->where('urutan',$notasiku->urutan+1)->first();
		    
			$terkirim = DB::table('surat_idv')->where('parent_table',$surat->parent_table)->where('parent_id',$surat->parent_id)->where('cms_privilege_id',$notasinext->id_cms_privileges)->first();
	        if($terkirim){
	            DB::table('surat_idv')->where('parent_table',$surat->parent_table)->where('parent_id',$surat->parent_id)->where('id','>',$id)->delete();
	            DB::table($surat->parent_table)->where('id',$surat->parent_id)->update(['nomor'=>null]);
	           // CRUDBooster::redirectBack('Permohonan sudah diteruskan !','warning');
	        }

			//  dd(Request::input('pejabat_id'));
			DB::table($surat->parent_table)->where('id',$parent->id)->update(['status_id'=>3,'updated_by' => CRUDBooster::myId()]);
			
			$notasiprev = DB::table('notasi_surat')->where('id_surat',$surat->jenis_surat_id)->where('urutan','<=',$notasiku->urutan)->get();
			foreach($notasiprev as $np){
				DB::table('surat_idv')->where('cms_privilege_id',$np->id_cms_privileges)->where('jenis_surat_id',$np->id_surat)->where('parent_id',$parent->id)->update(['status_id'=>3,'updated_by' => CRUDBooster::myId() ]); 
			}
			
			
			
			DB::table('surat_idv')->insert([
						'tanggal' => now(),
						'parent_table' => $surat->parent_table,
						'parent_id' => $surat->parent_id,
						'cms_privilege_id' => $notasinext->id_cms_privileges,
						'status_req' => $notasinext->aksi_diperlukan_id,
						'status_id' => 1,
						'jenis_surat_id' => $surat->jenis_surat_id,
						'sender_id' => $surat->sender_id,
						'sender_priv' =>  $surat->sender_priv,
						'nik' => $surat->nik,
						'nama_lgkp' => $surat->nama_lgkp,
						'tmpt_lhr' => $surat->tmpt_lhr,
						'tgl_lhr' => $surat->tgl_lhr,
						'alamat' => $surat->alamat,
						'agama' => $surat->agama,
						'status_perkawinan' => $surat->status_perkawinan,
						'rt' => $surat->rt,
						'rw' => $surat->rw,
						'village_id' => $surat->village_id,
						'district_id' => $surat->district_id,
						'regency_id' => $surat->regency_id,
						'province_id' => $surat->province_id,
						'jk' => $surat->jk,
						'pekerjaan' => $surat->pekerjaan,
						'no_telp' => $surat->no_telp,
						'keperluan' => $surat->keperluan,
						'next_priv' => $notasinext->id_cms_privileges,
						'created_at' => $surat->created_at,
						'updated_by' => CRUDBooster::myId(),
						'updated_by_priv' => CRUDBooster::myPrivilegeId(),
						'perusahaan_id' => $surat->perusahaan_id,
					]);

			CRUDBooster::sendNotifikasi(0,$notasinext->id_cms_privileges,CRUDBooster::myPrivilegeName() . ' Meneruskan permohonan ' . $jenis_surat->nama_surat,CRUDBooster::adminPath('surat_idv'));	
			return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan ' . $id .' sudah berhasil diteruskan.','success');
		}
		
		public function postTeruskan($id,$teruskan=false){
		  //  dd(Request::input());
		    $surat = DB::table('surat_idv')->where('id',$id)->first();
		    $parent = DB::table($surat->parent_table)->where('id',$surat->parent_id)->first();
		    $jenis_surat = DB::table('surat')->where('id',$surat->jenis_surat_id)->first();
		    $notasiku = DB::table('notasi_surat')->where('id_surat',$surat->jenis_surat_id)->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
    		$notasinext = DB::table('notasi_surat')->where('id_surat',$surat->jenis_surat_id)->where('urutan',$notasiku->urutan+1)->first();
		    
		    $terkirim = DB::table('surat_idv')->where('parent_table',$surat->parent_table)->where('parent_id',$surat->parent_id)->where('cms_privilege_id',$notasinext->id_cms_privileges)->first();
	        if($terkirim){
	            DB::table('surat_idv')->where('parent_table',$surat->parent_table)->where('parent_id',$surat->parent_id)->where('id','>',$id)->delete();
	            DB::table($surat->parent_table)->where('id',$surat->parent_id)->update(['nomor'=>null]);
	           // CRUDBooster::redirectBack('Permohonan sudah diteruskan !','warning');
	        }
			$eksis = DB::table($surat->parent_table)->where('id',$surat->parent_id)->where('updated_by',$surat->parent_id)->where('nomor',Request::input('nomor'))->first();
			if($eksis){
				CRUDBooster::redirectBack('Nomor Sudah Dipakai !','warning');
			}else{
				//  dd(Request::input('pejabat_id'));
				if($surat->parent_tabel=='perjanjian_kerja_waktu_tertentu'){
    				DB::table($surat->parent_table)->where('id',$parent->id)->update([
    				    'nomor' => Request::input('nomor') ,
    				    'pejabat_id' => Request::input('pejabat_id'),
    				    
    				    'nomor_depan_child' => Request::input('nomor_depan_child'),
    				    'nomor_terakhir_child' => Request::input('nomor_terakhir_child'),
    				    'nomor_belakang_child' => Request::input('nomor_belakang_child'),
    				    
    				    'status_id'=>3,
    				    'updated_by' => CRUDBooster::myId()
    				]);
				}else{
				    DB::table($surat->parent_table)->where('id',$parent->id)->update([
    				    'nomor' => Request::input('nomor') ,
    				    'pejabat_id' => Request::input('pejabat_id'),
    				    
    				    'status_id'=>3,
    				    'updated_by' => CRUDBooster::myId()
    				]);
				}
				
				$notasiprev = DB::table('notasi_surat')->where('id_surat',$surat->jenis_surat_id)->where('urutan','<=',$notasiku->urutan)->get();
				foreach($notasiprev as $np){
					DB::table('surat_idv')->where('cms_privilege_id',$np->id_cms_privileges)->where('jenis_surat_id',$np->id_surat)->where('parent_id',$parent->id)->update(['status_id'=>3,'updated_by' => CRUDBooster::myId(),'nomor' => Request::input('nomor') ]); 
				}
				
				if(Request::input('tanggal')){
					$tanggal = Request::input('tanggal');
					DB::table('surat_idv')->where('id',$id)->update(['tanggal'=>$tanggal]);
				}else{
					$tanggal = now();
				}
				
				
				if($teruskan){
    				DB::table('surat_idv')->insert([
    							'tanggal' => $tanggal,
    							'parent_table' => $surat->parent_table,
    							'parent_id' => $surat->parent_id,
    							'cms_privilege_id' => $notasinext->id_cms_privileges,
    							'status_req' => $notasinext->aksi_diperlukan_id,
    							'status_id' => 1,
    							'jenis_surat_id' => $surat->jenis_surat_id,
    							'sender_id' => $surat->sender_id,
    							'sender_priv' =>  $surat->sender_priv,
    							'nik' => $surat->nik,
    							'nama_lgkp' => $surat->nama_lgkp,
    							'tmpt_lhr' => $surat->tmpt_lhr,
    							'tgl_lhr' => $surat->tgl_lhr,
    							'alamat' => $surat->alamat,
    							'agama' => $surat->agama,
    							'status_perkawinan' => $surat->status_perkawinan,
    							'rt' => $surat->rt,
    							'rw' => $surat->rw,
    							'village_id' => $surat->village_id,
    							'district_id' => $surat->district_id,
    							'regency_id' => $surat->regency_id,
    							'province_id' => $surat->province_id,
    							'jk' => $surat->jk,
    							'pekerjaan' => $surat->pekerjaan,
    							'no_telp' => $surat->no_telp,
    							'keperluan' => $surat->keperluan,
    							'next_priv' => $notasinext->id_cms_privileges,
    							'created_at' => $surat->created_at,
    							'updated_by' => CRUDBooster::myId(),
    							'nomor' => Request::input('nomor'),
    							'gen_pdf' => $surat->gen_pdf,
    							'updated_by_priv' => CRUDBooster::myPrivilegeId(),
    							'target_id' => Request::input('target_id'),
    							'perusahaan_id' => $surat->perusahaan_id,
    						]);
    						
        				CRUDBooster::sendNotifikasi(Request::input('target_id'),$notasinext->id_cms_privileges,CRUDBooster::myPrivilegeName() . ' Meneruskan permohonan ' . $jenis_surat->nama_surat,CRUDBooster::adminPath('surat_idv'));
                        
                        $notified_user = array();
                        $next_notified = DB::table('multi_privs')
                                        ->join('cms_users','cms_users.id','multi_privs.cms_users_id')
                                        ->where('multi_privs.cms_privileges_id',$notasinext->id_cms_privileges)
                                        ->where('cms_users.village_id',$surat->village_id)
                                        ->selectRaw('multi_privs.*,cms_users.no_telp')
                                        ->get();
                                        
                        
                        foreach($next_notified as $neno){
                            array_push($notified_user,$neno->cms_users_id);
                            if($neno->no_telp!=null){
                                
                                $subtelp = substr($neno->no_telp,0,1);
                                if($subtelp == 0){
                                    $subtelp = substr_replace($neno->no_telp,"62",0,1);
                                    $chat_id = $subtelp . "@c.us";
                                }else{
                                    $chat_id = $d->no_telp . "@c.us";
                                }
                                
                                DB::table('wa_notif')->insert([
                                    'warga_bjb_id'=>CRUDBooster::idToWarga($neno->cms_users_id)->id,
                                    'cms_users_id'=> $neno->cms_users_id,
                                    'no_telp' => $neno->no_telp,
                                    'chat_id'=>$chat_id,
                                    'isi'=> CRUDBooster::myPrivilegeName() . " " .  CRUDBooster::myName() . " meneruskan permohonan ". $jenis_surat->nama_surat . " Nomor " . Request::input('no_sk_rt') . " atas nama " . $surat->nama_lgkp . ". Silahkan masuk ke SIAPKK " . CRUDBooster::publicPath()
                                    ]);
                        }
                    }
                    
				}
                    
                    if(Request::input('nomor')){
                        DB::table('surat')->where('id',$surat->jenis_surat_id)->update(['nomor_terakhir'=>Request::input('nomor_terakhir')]);
                    }
                    
                   
                    
    		      //  
    		      if($notasiku->aksi_diperlukan_id==3){
    		        $this->getCetakSurat($id,0,true);
    		      }else{
    		        return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan ' . $id .' sudah berhasil diteruskan.','success');   
    		      }
		    }
		  
		}
		
		public function getCetakSurat($id,$gen=0,$pdf=false){
		    setlocale(LC_TIME, 'id_ID');
		    setlocale(LC_ALL, 'IND');
		    Carbon::setlocale('id');
		    
		    $surat_masuk = DB::table('surat_idv')
							->join('surat','surat_idv.jenis_surat_id','=','surat.id')
							->leftJoin('cms_moduls','surat.model','=','cms_moduls.id')
							->where('surat_idv.id',$id)
							->select('surat_idv.*','surat.nama_surat', 'surat.model', 'surat.template_file','cms_moduls.path')
							->first();
							
			$parent_data = DB::table($surat_masuk->parent_table)
        		                ->where($surat_masuk->parent_table.'.id',$surat_masuk->parent_id)
        		                ->first();
        		                
		    $jenis_surat = DB::table('surat')->where('id',$surat_masuk->jenis_surat_id)->first();
		    $perusahaan = DB::table('perusahaan')->where('id',$parent_data->perusahaan_id)->first();
		    $modul = DB::table('cms_moduls')->where('id',$jenis_surat->model)->first();
		    
		    $pejabat = DB::table('pejabat')
		                        ->join('jabatan','pejabat.jabatan_id','jabatan.id')
		                        ->where('pejabat.id',$parent_data->pejabat_id)->first();
		    if(Schema::hasTable($surat_masuk->parent_table . '_child')){             
    		    $child = DB::table($surat_masuk->parent_table . '_child')
    		                        ->where('parent_id',$surat_masuk->parent_id)
    		                        ->get();
		    }
		                        
		    $mediator = DB::table('pejabat')
		                        ->join('pangkat','pejabat.pangkat_id','pangkat.id')
		                        ->where('pejabat.user_id',CRUDBooster::myId())->first();
		    
		  //  dd($pejabat);
		    
		    $notasiku = DB::table('notasi_surat')->where('id_surat',$surat_masuk->jenis_surat_id)->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
        	//hapus surat_idv di atas saya jika gen =1
        
        		                
            //if($reprint==0){
    		    $path = $surat_masuk->template_file;
    			$fileName = storage_path('app/' . $path);
    			$file = basename($path);
    			$file = basename($path , ".docx");
    			
  
    			
    			$templateProcessor = new WORD\TemplateProcessor($fileName);
    			
    			
    			$templateProcessor->setValue('nomor', preg_replace( '/&/', '&amp;', $parent_data->nomor ));
    			
    			$templateProcessor->setValue('nama_perusahaan', $perusahaan->nama_perusahaan);
    			
    			$templateProcessor->setValue('alamat_perusahaan', $perusahaan->alamat_perusahaan);
    			
    			$templateProcessor->setValue('jenis_usaha', $perusahaan->sektor_perusahaan_id);
    			
    			$date = strftime( "%d %B %Y", strtotime($surat_masuk->tgl_lhr));
    			
    			$templateProcessor->setValue('keperluan', $parent_data->peruntukan);
    			
    			//catatan masih membuat doc error
    // 			dd($parent_data->catatan);
    // 			$templateProcessor->setValue('catatan', $parent_data->catatan);
    
                $templateProcessor->setValue('telp_perusahaan', $perusahaan->telp_perusahaan);
    			
    			$templateProcessor->setValue('keterangan', $parent_data->keterangan);
    			
    			$templateProcessor->setValue('masa_berlaku', $jenis_surat->masa_berlaku);
    			
    			

    			$date_pernyataan = strftime( "%d %B %Y", strtotime($surat_masuk->tanggal));
    			
    			$tgl_pernyataan = Carbon::parse($date_pernyataan)->formatLocalized("%d %B %Y");

    			$templateProcessor->setValue('tanggal', $tgl_pernyataan);
    			
    			$tanggal=date_create($surat_masuk->tanggal);
    			
    			date_add($tanggal,date_interval_create_from_date_string( 365 * $jenis_surat->masa_berlaku . " days"));
    			
    			$date_expired = strftime( "%d %B %Y", date_timestamp_get($tanggal));
    			
    			$tgl_expired = Carbon::parse($date_expired)->formatLocalized("%d %B %Y");
    			
    			$templateProcessor->setValue('tanggal_exp', $tgl_expired);
    			
    			
    			$templateProcessor->setValue('jabatan', $pejabat->jabatan);
    			
    			$templateProcessor->setValue('tag_to_sign', "#");
    			
    			$templateProcessor->setValue('nama_ttd', $pejabat->nama_pejabat);
    			$templateProcessor->setValue('nip_ttd', $pejabat->nip_pejabat);
    			
    			$templateProcessor->setValue('nama_pembuat_data', $mediator->nama_pejabat);
    			
    			$templateProcessor->setValue('pangkat_pembuat_data', $mediator->pangkat);
    			$templateProcessor->setValue('nip_pembuat_data', $mediator->nip_pejabat);
    			
    // 			dd($mediator);
    			
    			if($child){
    			    $replacements = array();
                    foreach($child as $index => $ch){
                    	array_push($replacements,array(
                    	    'no' => $index+1, 
                    	    'nama_pekerja' => $ch->nama,
                    	    'jab_pekerja' => $ch->jabatan, 
                    	    'upah_pekerja' => number_format( $ch->upah,0), 
                    	    'tgl_ttd_pwkt' => CRUDBooster::localDate($ch->tanggal_tandatangan),
                    	    'tgl_ctt_pwkt' => CRUDBooster::localDate($ch->tanggal_pencatatan), 
                    	    'masa_berlaku_pwkt' => CRUDBooster::localDate($ch->berlaku_mulai) . ' s.d ' . CRUDBooster::localDate($ch->berlaku_sampai), 
                    	    'nomor_tgl_pwkt' => $ch->nomor_pencatatan, 
                    	    'ket_pekerja' => $ch->keterangan
                    	    )
                    	);
                    }
                    // dd($replacements);
                    $templateProcessor->cloneBlock('detail_pekerja', count($replacements), true, false, $replacements);
    			}
    			
    			
    			
    			
    			
    // 			$kunci = CRUDBooster::generateRandomString(17);
    			
    			
    // 			$qrfolder = 'uploads/' . CRUDBooster::myId() . '/' . date("Y") . '-' . date("m");
    //             $qrpath = 'uploads/' . CRUDBooster::myId() . '/' . date("Y") . '-' . date("m") . '/' . $kunci . '.png'; 
    //             $realqrpath = storage_path('app/'.$qrpath);
    //             if (!file_exists(storage_path('app/'.$qrfolder))) {
    //                 mkdir(storage_path('app/'.$qrfolder), 0755, true);
    //             }
    //             $qr = new QRCodeProv();
    //             $qr->makeqr($text = 'https://bjb.city/' . $kunci ,$path = storage_path('app/'.$qrpath));
                
    //             $templateProcessor->setImageValue(
    //                 'qr',
    //                 array('path' => $realqrpath, 'width' => 100, 'height' => 100, 'ratio' => false)
    //             );
                
                // $templateProcessor->setImageValue(
                //     'footer',
                //     array('path' => storage_path('app/'.CRUDBooster::getSetting('logo_bsre')), 'width' => 100, 'height' => 58, 'ratio' => false)
                //     );
                    
                // $templateProcessor->setValue(
                //     'footer_text',
                //     'Dokumen ini akan/telah ditandatangani secara elektronik menggunakan sertifikat elektronik yang diterbitkan oleh Balai Sertifikasi Elektronik (BSrE), BSSN.'
                //     );
    			
    // 			$nama_file = $surat_masuk->parent_table .'-'. str_replace("/","-",$surat_masuk->nomor) .'-'. $id;
    
                $nama_file = $surat_masuk->parent_table . $id;
    			$nama_file_surat = $nama_file . '.docx';
    			
    			$file = public_path('surat_gen/'. $nama_file_surat);
    			$path = storage_path('app/uploads/0/'. date('Y') . '-' . date('m') . '/surat_gen/'  );
    			
 
                if (!file_exists($path)) { 
                    mkdir($path, 0777, true);
                }
    			
    			
    			if (file_exists($path . $nama_file_surat)) {
                   unlink($path . $nama_file_surat);
                }
    			$templateProcessor->saveAs($path . $nama_file_surat);
    			
    			if($pdf){
    			    $durl = CRUDBooster::convertPdf($path . $nama_file_surat,$nama_file);
    			    $dlurl = CRUDBooster::downloadGenPdf($durl);
    			    DB::table('surat_idv')->where('jenis_surat_id',$surat_masuk->jenis_surat_id)->where('parent_id',$parent_data->id)->update(['status_id'=>3,'gen_doc'=>'uploads/0/'. date('Y') . '-' . date('m') .'/surat_gen/'.$nama_file_surat,'gen_pdf'=>$dlurl,'updated_by' => CRUDBooster::myId()]); 
    			    DB::table($surat_masuk->parent_table)->where('id',$surat_masuk->parent_id)->update(['gen_doc'=>'uploads/0/'. date('Y') . '-' . date('m') .'/surat_gen/'.$nama_file_surat,'gen_pdf'=>$dlurl,'updated_by' => CRUDBooster::myId()]); 
		            
		            if($gen==1){
        	            return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Dokumen ' . $id .' berhasil dibuat ulang.','success');
        	        }else{
        	           return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan ' . $id .' berhasil Dibuat.','success');
        	        }
		        }else{
		            DB::table('surat_idv')->where('jenis_surat_id',$surat_masuk->jenis_surat_id)->where('parent_id',$parent_data->id)->update(['status_id'=>3,'gen_doc'=>'uploads/0/'. date('Y') . '-' . date('m') .'/surat_gen/'.$nama_file_surat,'updated_by' => CRUDBooster::myId()]); 
		            DB::table($surat_masuk->parent_table)->where('id',$surat_masuk->parent_id)->update(['gen_doc'=>'uploads/0/'. date('Y') . '-' . date('m') .'/surat_gen/'.$nama_file_surat,'updated_by' => CRUDBooster::myId()]);
		            if($gen==1){
        	            return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Dokumen ' . $id .' berhasil buat ulang.','success');
        	        }else{
        	           return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Dokumen ' . $id .' berhasil Generate.','success');
        	           //return CRUDBooster::redirect(CRUDBooster::adminPath($surat_masuk->parent_table . "/edit/" . $surat_masuk->parent_id . "?command=proses&return_url=" . CRUDBooster::adminPath('surat_idv/teruskan/'.$id.'/'.$notasiku->aksi_diperlukan_id)),'Dokumen ' . $id .' berhasil di buat.','success');
        	        }
		        }
		}
		
		
		public function postCetakSuratDua($id,$notif=true,$reprint=0){
		    setlocale(LC_TIME, 'id_ID');
		    setlocale(LC_ALL, 'IND');
		    Carbon::setlocale('id');
		    
		    
		    $surat_masuk = DB::table('surat_idv')
							->join('surat','surat_idv.jenis_surat_id','=','surat.id')
							->join('districts','surat_idv.district_id','=','districts.id')
							->join('villages','surat_idv.village_id','=','villages.id')
							->leftJoin('cms_moduls','surat.model','=','cms_moduls.id')
							->leftJoin('layanan','surat.model','=','layanan.jenis_surat_id')
							->where('surat_idv.id',$id)
							->select('surat_idv.*','surat_idv.district_id as kec_id', 'surat_idv.village_id as kel_id', 'districts.name as kecamatan', 'villages.name as kelurahan', 'surat.kode', 'surat.nama_surat', 'layanan.kode_depan', 'surat.model', 'surat.template_file','cms_moduls.path', 'layanan.jumlah_digit')
							->first();
			
			if($surat_masuk->status_id < 3 || $reprint=1){				
    		    if(Schema::hasColumn($surat_masuk->parent_table,'satuan_id')){
        		    $rel_data = DB::table($surat_idv->parent_table)
        		                ->join('satuan','satuan.id',$surat_idv->parent_table.'.satuan_id')
        		                ->where($surat_idv->parent_table.'.id',$surat_idv->parent_id)
        		                ->first();
    		    }else{
    		        $rel_data = DB::table($surat_masuk->parent_table)
        		                ->where($surat_masuk->parent_table.'.id',$surat_masuk->parent_id)
        		                ->first();
    		    }
    		    
    		    
    		    
    		    $surat = DB::table('surat')->where('id',$surat_masuk->jenis_surat_id)->first();
    		    
    		    $pejabat = DB::table('pejabat')->join('jabatan','jabatan.id','pejabat.jabatan_id')->where('pejabat.id',Request::input('penandatangan'))->first();
    		    
    		    if(!$pejabat){
    		        $pejabat = DB::table('pejabat')->join('jabatan','jabatan.id','pejabat.jabatan_id')->where('pejabat.id',$surat_masuk->pejabat_id)->first();
    		    }
    		    
    		    $kantor = DB::table('kantor')
    							->where('district_id',$surat_masuk->district_id)
    							->where('village_id',$surat_masuk->village_id)
    							->first();
    			
    			$layanan = DB::table('layanan')
    						->where('jenis_surat_id',$surat_masuk->jenis_surat_id)
    						->where('village_id',CRUDBooster::me()->village_id)
    						->first();
    			
    			if(!Request::input('nomor_surat')){
    		        $nomor_surat = $surat_masuk->nomor;
    		        $statusid = 7;
    		    }else{
    		        $nomor_surat = $layanan->kode_depan . Request::input('nomor_surat') . $layanan->kode_belakang;
    		        $statusid = 1;
    		    }
    						
    			$nomor_surat_lain = DB::table($surat_masuk->parent_table)->where('nomor', $nomor_surat)->where('id','<>', $rel_data->id)->first();
    			//dd($nomor_surat_lain);
    		     if($nomor_surat_lain){
        		    CRUDBooster::redirectBack('Surat nomor ' . $nomor_surat . ' sudah dipakai !');
    		     }
    		    
    		    if($reprint==1){
    		        if (is_file(public_path($surat_masuk->gen_pdf))){
                        unlink(public_path($surat_masuk->gen_pdf));
                    }
                    if (is_file(public_path($surat_masuk->gen_doc))){
                        unlink(public_path($surat_masuk->gen_doc));
                    }
    		    }
    		    
    		    
    		   
    		    
    		    $notasiku = DB::table('notasi_surat')->where('id_surat',$surat_masuk->jenis_surat_id)->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
    			
        		$notasinext = DB::table('notasi_surat')->where('id_surat',$surat_masuk->jenis_surat_id)->where('urutan',$notasiku->urutan+1)->first();
    		    
    		    $terkirim = DB::table('surat_idv')->where('parent_table',$surat->parent_table)->where('parent_id',$surat->parent_id)->where('cms_privilege_id',$notasinext->id_cms_privileges)->first();
    	        if($terkirim){
    	            CRUDBooster::redirectBack('Permohonan sudah diteruskan !','warning');
    	        }
    		    
    		     
    		    //if($reprint==0){
    		    $path = $surat->template_file;
    			$fileName = storage_path('app/' . $path);
    			$file = basename($path);
    			$file = basename($path , ".docx");
    			
    			//dd($file);
    			
    			$templateProcessor = new WORD\TemplateProcessor($fileName);
    			
    			
    			$templateProcessor->setValue('nomor_surat', $nomor_surat);
    			
    			$templateProcessor->setValue('jumlah', $rel_data->jumlah);
    			
    			$templateProcessor->setValue('satuan', $rel_data->satuan);
    			
    			$templateProcessor->setValue('jenis', $rel_data->jenis_produk);
    			
    			$templateProcessor->setValue('tanda_khusus', $surat_masuk->tanda_khusus);
    			
    			$templateProcessor->setValue('warna', $surat_masuk->warna);
    			
    			$templateProcessor->setValue('nama', $surat_masuk->nama_lgkp);
    			
    			$templateProcessor->setValue('nik', $surat_masuk->nik);
    			
    			$templateProcessor->setValue('tempat_lahir', $surat_masuk->tmpt_lhr);
    			
    			$date = strftime( "%d %B %Y", strtotime($surat_masuk->tgl_lhr));
    			
    			$tgl = Carbon::parse($surat_masuk->tgl_lhr);
    			
    			// dd($date);
    			
    			$templateProcessor->setValue('tanggal_lahir', $date);
    			
    			$templateProcessor->setValue('alamat', $surat_masuk->alamat );
    			
    			$templateProcessor->setValue('tujuan_pengiriman', $rel_data->tujuan_pengiriman );
    			
    			if($surat_masuk->jk == "L"){
    				$templateProcessor->setValue('jenis_kelamin', 'Laki-laki');
    			}else{
    				$templateProcessor->setValue('jenis_kelamin', 'Perempuan');
    			}	
    			
    		
    			$templateProcessor->setValue('pekerjaan', $surat_masuk->pekerjaan);
    			
    			$templateProcessor->setValue('status_perkawinan', $surat_masuk->status_perkawinan);
    			
    			$templateProcessor->setValue('agama', $surat_masuk->agama);
    			
    			$templateProcessor->setValue('kecamatan', $surat_masuk->kecamatan);
    			
    			$templateProcessor->setValue('kelurahan', $surat_masuk->kelurahan);
    			
    			$templateProcessor->setValue('rt', $surat_masuk->rt);
    			
    			$templateProcessor->setValue('rw', $surat_masuk->rw);
    			
    			//$templateProcessor->setValue('alamat_kantor', $kantor->alamat . ' Telp : ' . $kantor->no_telp);
    			
    			$templateProcessor->setValue('alamat_kantor', $kantor->alamat );
    			
    			$templateProcessor->setValue('no_sk_rt', $rel_data->no_sk_rt);
    			
    			$tgl_sk_date = strftime( "%d %B %Y", strtotime($rel_data->tgl_sk_rt));
    			
    			$templateProcessor->setValue('tgl_sk_rt', $tgl_sk_date);
    			
    			$templateProcessor->setValue('keperluan', $rel_data->keperluan);
    			
    			$templateProcessor->setValue('keterangan', $rel_data->keterangan);
    			
    			
    			// foreach($unggahan as $unggah){
    				// DB::Table('unggahan')
    					// ->where('id',$unggah->id)
    					// ->update(['is_verified' => Request::input('verifikasi-'.$unggah->id)]);
    				
    				// if(Request::input('verifikasi-'.$unggah->id) == 1){
    					// $templateProcessor->setValue(Str::slug($unggah->deskripsi,'_'), $unggah->file);
    				// }
    			// }
    			
    			
    // 			$created_date = strftime( "%d %B %Y", strtotime($surat->created_at));
    			
    // 			$templateProcessor->setValue('tanggal', $created_date);
    			
    // 			$expired_at = strftime( "%d %B %Y", strtotime($surat->expired_at));
    			
    // 			$templateProcessor->setValue('masa_berlaku', $expired_at);
    			
    			$date_pernyataan = strftime( "%d %B %Y", strtotime(Request::input('tanggal')));
    			
    			$templateProcessor->setValue('tanggal', $date_pernyataan);
    			$templateProcessor->setValue('jabatan', $pejabat->jabatan);
    			
    			$templateProcessor->setValue('tag_to_sign', Request::input('tag_to_sign'));
    			
    			$templateProcessor->setValue('nama_ttd', $pejabat->nama_pejabat);
    			$templateProcessor->setValue('nip_ttd', $pejabat->nip_pejabat);
    			
    			$kunci = CRUDBooster::generateRandomString(17);
    			
    			
    			$qrfolder = 'uploads/' . CRUDBooster::myId() . '/' . date("Y") . '-' . date("m");
                $qrpath = 'uploads/' . CRUDBooster::myId() . '/' . date("Y") . '-' . date("m") . '/' . $kunci . '.png';
                $realqrpath = storage_path('app/'.$qrpath);
                if (!file_exists(storage_path('app/'.$qrfolder))) {
                    mkdir(storage_path('app/'.$qrfolder), 0755, true);
                }
                $qr = new QRCodeProv();
                $qr->makeqr($text = 'https://bjb.city/' . $kunci ,$path = storage_path('app/'.$qrpath));
                
                $templateProcessor->setImageValue(
                    'qr',
                    array('path' => $realqrpath, 'width' => 100, 'height' => 100, 'ratio' => false)
                );
                
                $templateProcessor->setImageValue(
                    'footer',
                    array('path' => storage_path('app/'.CRUDBooster::getSetting('logo_bsre')), 'width' => 100, 'height' => 58, 'ratio' => false)
                    );
                    
                $templateProcessor->setValue(
                    'footer_text',
                    'Dokumen ini akan/telah ditandatangani secara elektronik menggunakan sertifikat elektronik yang diterbitkan oleh Balai Sertifikasi Elektronik (BSrE), BSSN.'
                    );
    			
    			$nama_file = $surat_masuk->parent_table . $surat->kode . $id;
    			$nama_file_surat = $nama_file . '.docx';
    			
    			$file = public_path('surat_gen/'. $nama_file_surat);
    			$path = storage_path('surat_gen/'. $nama_file_surat);
    			
    			
    			
    			$templateProcessor->saveAs($file);
    			
    			
    			$durl = CRUDBooster::convertPdf($file,$nama_file);
    			
    		    //dd($durl);
    			
    			sleep(2);
    			
    			
    			if($durl){
    			    $newgenpdf = CRUDBooster::downloadGenPdf($durl);
    			}else{
    			   $newgenpdf = null; 
    			}
    			
    			$newhandap = DB::table('bahandap')->insertGetId(['kunci'=>$kunci,'redurl'=>CRUDBooster::adminPath($newgenpdf),'updated_by'=>CRUDBooster::myId(),'updated_by_priv'=>CRUDBooster::myPrivilegeId(),'gen'=>1,'hit_limit'=>0]);
    			
    		//	DB::table('surat_idv')->where('id',$id)->update(['gen_doc'=>'surat_gen/'. $nama_file_surat ,'gen_pdf'=>$newgenpdf ,'status_id'=>3,'status_by'=>CRUDBooster::myId(),'status_by_priv'=>CRUDBooster::myPrivilegeId()]);
    			DB::table($surat_masuk->parent_table)->where('id',$surat_masuk->parent_id)->update(['nomor'=> $nomor_surat,'gen_doc'=>'surat_gen/'.$nama_file_surat,'gen_pdf'=>$newgenpdf,'bahandap_id'=>$newhandap,'updated_by' => CRUDBooster::myId(),'pejabat_id'=>$pejabat->id]);
    			
    			 
        		
        		$notasiprev = DB::table('notasi_surat')->where('id_surat',$surat_masuk->jenis_surat_id)->where('urutan','<=',$notasiku->urutan)->get();
        		
    	        foreach($notasiprev as $np){
    	           DB::table('surat_idv')->where('cms_privilege_id',$np->id_cms_privileges)->where('jenis_surat_id',$np->id_surat)->where('parent_id',$rel_data->id)->update(['status_id'=>3,'gen_doc'=>'surat_gen/'.$nama_file_surat,'gen_pdf'=>$newgenpdf,'updated_by' => CRUDBooster::myId()]); 
    	        }
    	        
    	        
        		
    	        //DB::table('surat_idv')->where('id',$id)->update(['status_id'=>3]);
    	        // send to next priv
    	        if($reprint==0){
        	        DB::table('surat_idv')->insert([
                                'parent_table' => $surat_masuk->parent_table,
                                'parent_id' => $surat_masuk->parent_id,
                                'cms_privilege_id' => $notasinext->id_cms_privileges,
                                'status_req' => $notasinext->aksi_diperlukan_id,
                                'status_id' => $statusid,
                            	'jenis_surat_id' => $surat_masuk->jenis_surat_id,
            					'sender_id' => $surat_masuk->sender_id,
            					'sender_priv' =>  $surat_masuk->sender_priv,
            					'nik' => $surat_masuk->nik,
            					'nama_lgkp' => $surat_masuk->nama_lgkp,
            					'tmpt_lhr' => $surat_masuk->tmpt_lhr,
            					'tgl_lhr' => $surat_masuk->tgl_lhr,
            					'alamat' => $surat_masuk->alamat,
            					'agama' => $surat_masuk->agama,
                    			'status_perkawinan' => $surat_masuk->status_perkawinan,
            					'rt' => $surat_masuk->rt,
            					'rw' => $surat_masuk->rw,
            					'village_id' => $surat_masuk->village_id,
            					'district_id' => $surat_masuk->district_id,
            					'regency_id' => $surat_masuk->regency_id,
            					'province_id' => $surat_masuk->province_id,
            					'jk' => $surat_masuk->jk,
            					'pekerjaan' => $surat_masuk->pekerjaan,
            					'no_telp' => $surat_masuk->no_telp,
            					'keperluan' => $surat_masuk->keperluan,
            					'next_priv' => $notasinext->id_cms_privileges,
            					'gen_doc' => 'surat_gen/'.$nama_file_surat,
            					'gen_pdf' => $newgenpdf,
            					'tag_to_sign' => Request::input('tag_to_sign'),
            					'created_at' => $surat_masuk->created_at,
                    			'updated_by' => CRUDBooster::myId(),
                    			'pejabat_id' =>$surat_masuk->pejabat_id,
                    			"no_sk_rt" => $surat_masuk->no_sk_rt,
                                "tgl_sk_rt" => $surat_masuk->tgl_sk_rt,
                                "nomor" => $nomor_surat,
            					"tanggal" => $surat_masuk->tanggal,
                            ]);
    	        }else{
    	            DB::table('surat_idv')
    	                    ->where('cms_privilege_id','>',5)
    	                    ->where('jenis_surat_id',$surat_masuk->jenis_surat_id)
    	                    ->where('parent_id',$rel_data->id)
    	                    ->update([
                            	'jenis_surat_id' => $surat_masuk->jenis_surat_id,
            					'sender_id' => $surat_masuk->sender_id,
            					'sender_priv' =>  $surat_masuk->sender_priv,
            					'nik' => $surat_masuk->nik,
            					'nama_lgkp' => $surat_masuk->nama_lgkp,
            					'tmpt_lhr' => $surat_masuk->tmpt_lhr,
            					'tgl_lhr' => $surat_masuk->tgl_lhr,
            					'alamat' => $surat_masuk->alamat,
            					'agama' => $surat_masuk->agama,
                    			'status_perkawinan' => $surat_masuk->status_perkawinan,
            					'rt' => $surat_masuk->rt,
            					'rw' => $surat_masuk->rw,
            					'village_id' => $surat_masuk->village_id,
            					'district_id' => $surat_masuk->district_id,
            					'regency_id' => $surat_masuk->regency_id,
            					'province_id' => $surat_masuk->province_id,
            					'jk' => $surat_masuk->jk,
            					'pekerjaan' => $surat_masuk->pekerjaan,
            					'no_telp' => $surat_masuk->no_telp,
            					'keperluan' => $surat_masuk->keperluan,
            					'next_priv' => $notasinext->id_cms_privileges,
            					'gen_doc' => 'surat_gen/'.$nama_file_surat,
            					'gen_pdf' => $newgenpdf,
            					'tag_to_sign' => $surat_masuk->tag_to_sign,
                    			'updated_by' => CRUDBooster::myId(),
                    			'pejabat_id' =>$surat_masuk->pejabat_id,
                    			"no_sk_rt" => $surat_masuk->no_sk_rt,
                                "tgl_sk_rt" => $surat_masuk->tgl_sk_rt,
                                "nomor" => $nomor_surat,
            					"tanggal" => $surat_masuk->tanggal,
                            ]);
    	            
    	        }
    			
    			//$newDokumen = DB::table('dokumen')->insertGetId(['']);
    			
    			//olah domain dinamis
    			//$data['localdocfile'] = storage_path('surat_gen/skck' . $id . '.docx');
    			
    			
    	        
    			
    // 			$headers = [
    //               'Content-Type' => 'application/docx',
    //           ];
    
               //return response()->download($file, $nama_file_surat, $headers);
               
               //notif WA Lurah
               
               if(!Request::input('nomor_surat')){
    		        $surat_idv = DB::table($this->table)->where("id",$id)->first();
        	        $nomor = explode("/",$nomor_surat);
        	        DB::table('layanan')->where("jenis_surat_id",$surat_idv->jenis_surat_id)
        	                            ->where("village_id",$surat_idv->village_id)
        	                            ->update(['no_terakhir'=>(int)$nomor[1]]);
    		    }else{
    		        DB::table('layanan')
    						->where('jenis_surat_id',$surat_masuk->jenis_surat_id)
    						->where('village_id',CRUDBooster::me()->village_id)
    						->update(['no_terakhir'=>Request::input('nomor_surat')]);
    		    }
               
    						
    			$notified_user = array();
    			
    			if($notif==true){			
        			$next_notified = DB::table('multi_privs')
                                    ->join('cms_users','cms_users.id','multi_privs.cms_users_id')
                                    ->where('multi_privs.cms_privileges_id',$notasinext->id_cms_privileges)
                                    ->where('cms_users.village_id',$surat_masuk->village_id)
                                    ->selectRaw('multi_privs.*,cms_users.no_telp')
                                    ->get();
                                    
                   // dd($next_notified);
                    
                    foreach($next_notified as $neno){
                        array_push($notified_user,$neno->cms_users_id);
                        if($neno->no_telp!=null){
                            
                            $subtelp = substr($neno->no_telp,0,1);
                            if($subtelp == 0){
                                $subtelp = substr_replace($neno->no_telp,"62",0,1);
                                $chat_id = $subtelp . "@c.us";
                            }else{
                                $chat_id = $d->no_telp . "@c.us";
                            }
                            
                            DB::table('wa_notif')->insert([
                                'warga_bjb_id'=>CRUDBooster::idToWarga($neno->cms_users_id)->id,
                                'cms_users_id'=> $neno->cms_users_id,
                                'no_telp' => $neno->no_telp,
                                'chat_id'=>$chat_id,
                                'isi'=> CRUDBooster::myPrivilegeName() . " Anda " .  CRUDBooster::myName() . " memverifikasi permohonan ". $surat->nama_surat . " atas nama " . $surat_masuk->nama_lgkp . " untuk di tandatangani." . " Silahkan masuk ke SIAPKK " . CRUDBooster::publicPath()
                                ]);
                        }
                    }
                    
        //             $config['id_cms_users'] = $notified_user;
        // 			$config['content'] = CRUDBooster::myName() . " memverifikasi permohonan ". $surat->nama_surat . " atas nama " . $surat_masuk->nama_lgkp . " untuk di tandatangani.";
        // 			$config['to'] = CRUDBooster::adminPath('surat_idv/lihat-surat/'.$id);
        			
        // 			CRUDBooster::sendNotification($config);
        			if($reprint==0){
        		        return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan ' . $id .' dikirim untuk di tandatangani.','success');
        			}else{
        			    return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan ' . $id .' digenerate ulang.','success');
        			}
        		}
			}else{
			    return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan ' . $id .' sudah di proses admin lain.','warning'); 
			}
			
				
			//to the viewer
			//$data['docfile'] = CRUDBooster::getSetting('domain') . '/surat/' . $surat->path . $id . '.docx';
			//$this->cbView('viewdoc',$data);
			//
		}
		
		public function getRePdf($id){
		    $suratidv = DB::table('surat_idv')->where('id',$id)->first();
		    $nama_file = basename($suratidv->gen_doc);
		    $file = public_path($suratidv->gen_doc);
		    $durl = CRUDBooster::convertPdf($file,$nama_file);
    			
		    //dd($durl);
			
			sleep(1);
			
			
			if($durl){
			    $newgenpdf = CRUDBooster::downloadGenPdf($durl);
			    DB::table('surat_idv')->where('parent_id',$suratidv->parent_id)->where('parent_table',$suratidv->parent_table)->update(['gen_pdf'=>$newgenpdf]);
			    DB::table($suratidv->parent_table)->where('id',$suratidv->parent_id)->update(['gen_pdf'=>$newgenpdf]);
			    CRUDBooster::redirectBack("Pdf berhasil di generate","success");
			}else{
			   $newgenpdf = null; 
			   CRUDBooster::redirectBack("Pdf gagal di generate","danger");
			}
		    //dd($newgenpdf);
		}
		
		public function postTte(){
	        $data = [];
	        $data['surat'] = DB::table('surat_idv')->where('id',Request::input('id'))->first();
	        $data['pemohon'] = DB::table('cms_users')->where('id',$data['surat']->sender_id)->first();
	        $data['warga'] = DB::table('warga_bjb')
            		        ->join('districts','warga_bjb.nama_kec','=','districts.id')
            				->join('villages','warga_bjb.nama_kel','=','villages.id')
            				->where('warga_bjb.nik',$data['pemohon']->nik)
            				->select('warga_bjb.*','villages.name as kelurahan','districts.name as  kecamatan')
		                    ->first();
	        $idv = DB::table($data['surat']->parent_table)->where('id',$data['surat']->parent_id)->first();
	        $jenis_surat = DB::table('surat')->where('id',$data['surat']->jenis_surat_id)->first();
	        
	        //dd($data['pengirim']);
	        $pdffolder = 'uploads/' . CRUDBooster::myId() . '/' . date("Y") . '-' . date("m");
	        if (!file_exists(storage_path('app/'.$pdffolder))) {
                mkdir(storage_path('app/'.$pdffolder), 0755, true);
            }
            
	        $esign = new Esign();
            $resp = $esign->sign($nik = CRUDBooster::me()->nik, $pass = Request::input('pass'), $pdf = $idv->gen_pdf, $tag = $data['surat']->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;
                
                $notasiku = DB::table('notasi_surat')->where('id_surat',$data['surat']->jenis_surat_id)->where('id_cms_privileges',CRUDBooster::myPrivilegeId())->first();
                $notasinext = DB::table('notasi_surat')->where('id_surat',$data['surat']->jenis_surat_id)->where('urutan',$notasiku->urutan+1)->get();
                
                if(sizeof($notasinext)<1){
                    DB::table($data['surat']->parent_table)->where('id',$data['surat']->parent_id)->update(['signed_pdf'=>$pdfpath ,'status_id'=>5,'updated_by' => CRUDBooster::myId()]);
                    //selesai all
                    DB::table('surat_idv')->where('parent_table',$data['surat']->parent_table)->where('cms_privilege_id','<>',5)->where('parent_id',$data['surat']->parent_id)->update(['status_id'=>5,'signed_pdf'=>$pdfpath,'updated_by' => CRUDBooster::myId()]);
                   
            		
            // 		$notasiprev = DB::table('notasi_surat')->where('id_surat',$data['surat']->jenis_surat_id)->where('urutan','<=',$notasiku->urutan)->get();
            // 		//dd($notasiprev);
        	   //     foreach($notasiprev as $np){
        	   //        DB::table('surat_idv')->where('cms_privilege_id',$np->id_cms_privileges)->where('jenis_surat_id',$np->id_surat)->where('parent_id',$rel_data->id)->update(['status_id'=>3,'signed_pdf'=>$pdfpath]); 
        	   //     }
                    
                    if($data['pemohon']->no_telp!=null){
                        $subtelp = substr($data['pemohon']->no_telp,0,1);
                        if($subtelp == 0){
                            $subtelp = substr_replace($data['pemohon']->no_telp,"62",0,1);
                            $chat_id = $subtelp . "@c.us";
                        }else{
                            $chat_id = $d->no_telp . "@c.us";
                        }
                        
                        DB::table('wa_notif')->insert([
                            'warga_bjb_id'=>$data['warga']->id,
                            'cms_users_id'=> $data['pemohon']->id,
                            'no_telp' => $data['pemohon']->no_telp,
                            'chat_id'=>$chat_id,
                            'isi'=>'Permohonan ' . $jenis_surat->nama_surat . ' anda sudah selesai, silahkan ketuk tautan berikut ' . CRUDBooster::publicPath($pdfpath)
                            ]);
                    }
                        
                    DB::table('bahandap')->where('id',$idv->bahandap_id)->update(['redurl'=>CRUDBooster::publicPath($pdfpath)]);
                    
                    CRUDBooster::redirect(CRUDBooster::mainpath('lihat-surat/'.Request::input('id')),$response->esign_message,"success");
                }else{
                    $notasinext = DB::table('notasi_surat')->where('id_surat',$data['surat']->jenis_surat_id)->where('urutan',$notasiku->urutan+1)->first();
                    
                    DB::table('surat_idv')->insert([
                            'parent_table' => $data['surat']->parent_table,
                            'parent_id' => $data['surat']->parent_id,
                            'cms_privilege_id' => $notasinext->id_cms_privileges,
                            'status_req' => $notasinext->aksi_diperlukan_id,
                            'status_id' => 1,
                        	'jenis_surat_id' => $data['surat']->jenis_surat_id,
        					'sender_id' => $data['surat']->sender_id,
        					'sender_priv' =>  $data['surat']->sender_priv,
        					'nik' => $data['surat']->nik,
        					'nama_lgkp' => $data['surat']->nama_lgkp,
        					'tmpt_lhr' => $data['surat']->tmpt_lhr,
        					'tgl_lhr' => $data['surat']->tgl_lhr,
        					'alamat' => $data['surat']->alamat,
        					'agama' => $data['surat']->agama,
                			'status_perkawinan' => $data['surat']->status_perkawinan,
        					'rt' => $data['surat']->rt,
        					'rw' => $data['surat']->rw,
        					'village_id' => $data['surat']->village_id,
        					'district_id' => $data['surat']->district_id,
        					'regency_id' => $data['surat']->regency_id,
        					'province_id' => $data['surat']->province_id,
        					'jk' => $data['surat']->jk,
        					'pekerjaan' => $data['surat']->pekerjaan,
        					'no_telp' => $data['surat']->no_telp,
        					'keperluan' => $data['surat']->keperluan,
        					'next_priv' => $notasinext->id_cms_privileges,
        					'gen_doc' => $data['surat']->gen_doc,
        					'gen_pdf' => $data['surat']->gen_pdf,
        					'signed_pdf' => $data['surat']->signed_pdf,
        					'created_at' => $data['surat']->created_at,
                			'updated_by' => CRUDBooster::myId()
        					
                        ]);
    			
    						
        			$notified_user = array();
        						
        			$next_notified = DB::table('multi_privs')
                                    ->join('cms_users','cms_users.id','multi_privs.cms_users_id')
                                    ->where('multi_privs.cms_privileges_id',$notasinext->id_cms_privileges)
                                    ->where('cms_users.village_id',$data['surat']->village_id)
                                    ->selectRaw('multi_privs.*,cms_users.no_telp')
                                    ->get();
                                    
                    //dd($next_notified);
                    
                    foreach($next_notified as $neno){
                        array_push($notified_user,$neno->cms_users_id);
                        if($neno->no_telp!=null){
                            
                            $subtelp = substr($neno->no_telp,0,1);
                            if($subtelp == 0){
                                $subtelp = substr_replace($neno->no_telp,"62",0,1);
                                $chat_id = $subtelp . "@c.us";
                            }else{
                                $chat_id = $d->no_telp . "@c.us";
                            }
                            
                            DB::table('wa_notif')->insert([
                                'warga_bjb_id'=>CRUDBooster::idToWarga($neno->cms_users_id)->id,
                                'cms_users_id'=> $neno->cms_users_id,
                                'no_telp' => $neno->no_telp,
                                'chat_id'=>$chat_id,
                                'isi'=> CRUDBooster::myPrivilegeName() . " Anda " .  CRUDBooster::myName() . " mengirim permohonan ". $jenis_surat->nama_surat . " atas nama " . $data['surat']->nama_lgkp . " untuk di tandatangani." . " Silahkan masuk ke SIAPKK " . CRUDBooster::publicPath()
                                ]);
                        }
                    }
                    
                    $config['id_cms_users'] = $notified_user;
        			$config['content'] = CRUDBooster::myName() . " memverifikasi permohonan ". $surat->nama_surat . " atas nama " . $surat_masuk->nama_lgkp . " untuk di tandatangani.";
        			$config['to'] = CRUDBooster::adminPath('surat_idv/lihat-surat/'.$id);
        			
        			CRUDBooster::sendNotification($config);
        			
        		    return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'Permohonan ' . $id .' dikirim untuk di tandatangani.','success');
                }
            }else{
                CRUDBooster::redirectBack($response->esign_message, "danger");
            }
        }


		public function getUploadTte($id){
			$data = [];
		    $data['surat'] = DB::table('surat_idv')->where('id',$id)->first();
		    $data['parent'] = DB::table($data['surat']->parent_table)->where('id',$data['surat']->parent_id)->first();
		    $data['jenis_surat'] = DB::table('surat')->where('id',$data['surat']->jenis_surat_id)->first();
		    $data['perusahaan'] = DB::table('perusahaan')->where('id',$data['parent']->perusahaan_id)->first();
		    $data['modul'] = DB::table('cms_moduls')->where('id',$data['jenis_surat']->model)->first();
		    $data['pejabat'] = DB::table('pejabat')
		                        ->join('jabatan','pejabat.jabatan_id','jabatan.id')
		                        ->where('pejabat.dinas_id',CRUDBooster::me()->dinas_id)
		                        ->selectRaw('pejabat.*, jabatan.jabatan')
		                        ->get();
		                        
		  
		                        
		    
		    $data['terkirim'] = DB::table('surat_idv')->where('parent_table',$data['surat']->parent_table)->where('parent_id',$data['surat']->parent_id)->where('id','>',$id)->first();

			$this->cbView('surat.form.upload',$data);
		}

		public function postUploadTte(){
            $suratidv = DB::table('surat_idv')->where('id',Request::input('id'))->first();
            $surat = DB::table($suratidv->parent_table)->where('id',$suratidv->parent_id)->first();
            // dd($surat);
            $file = CRUDBooster::uploadFile('eska');
            DB::table('surat_idv')->where('parent_table',$suratidv->parent_table)->where('parent_id',$suratidv->parent_id)->update(['signed_pdf'=>$file,'status_id'=>5,'updated_by'=>CRUDBooster::myId(),'updated_by_priv'=>47]);
	        
	        CRUDBooster::sendNotifikasi($surat->created_by,2,'Permohonan Anda Telah Disetujui.',CRUDBooster::adminPath('surat_idv'));
			return CRUDBooster::redirect(CRUDBooster::adminPath('surat_idv'),'File SK ' . Request::input('id') .' berhasil dikirim.','success');

		}


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


	}