<?php namespace App\Http\Controllers;

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

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

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

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

		    }

		    public function hook_query(&$query) {
		        //$query->leftJoin('homecare','homecare_media.homecare_id','homecare.id')->get();
		        $query->orderBy('created_at','DESC');
		    }

		    public function hook_after($postdata,&$result) {
		       if($postdata['status']){
		           foreach($result['data'] as $data){
		               $parent = DB::table('homecare')->where('id',$data->homecare_id)->first();
		               $data->nik = $parent->nik;
		               $data->nama = $parent->nama;
		               $data->alamat = $parent->alamat;
		               $data->status = $parent->status;
		               $pengirim = DB::table('cms_users')
		                        ->where('no_telp',$this->extNoTelp($parent->created_by))
		                        ->selectRaw('id,name,display_name,photo,no_telp,dinas_id')
		                        ->first();
		               $data->pengirim = $pengirim;
		               if($pengirim != null){
		                   $data->created_by = $pengirim->name;
		               }else{
		                   $data->created_by = $parent->created_by;
		               }
		               
		               $data->created_at = $parent->created_at;
		           }
		          
		       }
		    }
		    
		    public function extNoTelp($chat_id){
                $notelp = preg_split("/@/", $chat_id);
			    $notelp = substr_replace($notelp[0],"0",0,2);
			    
			    return $notelp;
            }

		}