<?php namespace App\Http\Controllers;

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

		class ApiListChatsController extends \crocodicstudio\crudbooster\controllers\ApiController {

		    function __construct() {    
				$this->table       = "komentar";        
				$this->permalink   = "list_chats";    
				$this->method_type = "get";    
		    }
		

		    public function hook_before(&$postdata) {
		        //This method will be execute before run the main process
		    }

		    public function hook_query(&$query) {
		        //This method is to customize the sql query
                $query->select(DB::raw('DISTINCT nama_table, key_id, user_id'));
		    }

		    public function hook_after($postdata,&$result) {
		        //This method will be execute after run the main process
                $detail = array();
                foreach($result['data'] as $data){
                    $qdetail = DB::table($data->nama_table)
                                ->where('id', $data->key_id)
                                ->first();
                                
                   if($data->nama_table=="grup"){
    			        $qdetail->nama =$qdetail->nama_grup;
    			        $qdetail->gambar_utama = "https://siapkk.banjarbarukota.go.id/".$qdetail->poto_grup;
    			    }else if($data->nama_table=="lokasi"){
    			        $qdetail->gambar_utama = "https://siapkk.banjarbarukota.go.id/".$qdetail->gambar_utama;
    			    }
    			    else if($data->nama_table=="informasi"){
    			        $qdetail->nama = $qdetail->judul;
    			        $qdetail->gambar_utama = "https://siapkk.banjarbarukota.go.id/".$qdetail->gambar_utama;
    			    }
                                
                    $terlibat = DB::table('komentar')
            					->where('nama_table',$data->nama_table)
            					->where('key_id',$data->key_id)
            					->where('user_id','<>',$data->user_id)
            					->distinct()
            					->get(['user_id']);
					
    				$tlb = array();
    				
    				foreach($terlibat as $t){
    					array_push($tlb,CRUDBooster::whoAmI($t->user_id)->nik);
    				    // if(CRUDBooster::whoAmI($t->user_id)->display_name){
    					   // array_push($tlb,CRUDBooster::whoAmI($t->user_id)->display_name);
    				    // }else{
    				    //     array_push($tlb,CRUDBooster::whoAmI($t->user_id)->name);
    				    // }
    				}
                    
                     $qdetail->terlibat = $tlb;
                     $qdetail->jterlibat = sizeof($terlibat);
                           
                    $qdetail->nama_table = $data->nama_table;
                   
                                
                    array_push($detail,$qdetail);
                    
                    $data->detail = $qdetail;
                }
                
                //$result['detail'] = $detail;
		    }

		}