<?php

namespace App\Modules\Catalogo\Models;

use Illuminate\Database\Eloquent\Model;
use App\Modules\Catalogo\Models\Entidad;
use DB;
class Entidad_service extends Model
{
	protected $table_id = 'entidad_services_has';
	protected $table ='entidad_services';
	public  function Create_services_has(){
		try { 
			foreach ($this->tables as $k => $val) {
				DB::table($this->table_id)->insert(['entidad_services_id'=>$val,'entidad_id'=>$this->entidad_id,'table_tipe'=>$k]);
		    }
	    } catch (\Exception $e) {
	    	report($e);
        	return false;
	    }
	}
	public  function Update_services_has(){
		try { 
			$update = DB::select("SELECT * FROM $this->table_id WHERE entidad_id = $this->entidad_id ");
			if (count($update) > 0 ) {
				foreach ($this->tables as $k => $val) {
					DB::update("UPDATE $this->table_id set entidad_services_id = ? where entidad_id = $this->entidad_id AND table_tipe = '$k' " , ["$val"]);
				}
			}else{
				$this->Create_services_has();
			}
	    } catch (\Exception $e) {
	    	report($e);
        	return false;
	    }
	}
	public  function Show_services_has_id($id){
		try { 
			return DB::table($this->table_id)
	        ->join($this->table, 'entidad_services_id', '=', 'entidad_services.id')
	        ->where('entidad_id',$id)
	        ->get();			
		} catch (\Exception $e) {
	    	report($e);
        	return false;
	    }
	}
	public function get_excerpt_entidad($id){
		try { 
			$entidad_services = $this::all();
			$staticservices = array('25','31','32','33');
			$services_relations = $this->Show_services_has_id($id);
			$entidad_services_get = array();
			$entidad_services_tables = array();
			foreach ($entidad_services as $k) {
				$result = false;
				$tables = false;
				foreach ($services_relations as $r) {
					if ($r->entidad_services_id == $k->id) {
						$entidad_services_get[] =  $r;
						$result = true;
					}
					if ($r->table_tipe == $k->table_tipe) {
						$tables = true;
					}
				}
				if ($tables == false) {
					$entidad_services_tables[] = $k->table_tipe;
				}
			}
			$x1 = $entidad_services_get;
			$x2 = json_decode(json_encode(array_unique($entidad_services_tables)), True);
			$entidad = ['services'=>$x1,'tables'=>$x2,'entidad_services'=>$entidad_services,'staticservices'=>$staticservices];
			return $entidad;
		} catch (\Exception $e) {
	    	report($e);
        	return false;
	    }
	}
	public function destroy_services_has($id){
		try { 
			$delete = DB::table($this->table_id)->where('entidad_id', '=', $id);
			if ($delete->count() > 0) {
				$delete->delete();
			}
		} catch (\Exception $e) {
	    	report($e);
        	return false;
	    }
	}
}
