<?php

namespace App\Modules\User\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Role;
use App\User;
use DB;
class Modules_user extends Model
{
    public $timestamps = false;
    protected $guarded = [];
    protected $fillable = [];
    protected $table_pivot = "modules_has_rol";
    protected $role;
    protected $user;
    function __construct(){
    	$this->role = new Role();
    	$this->user = new User();
    }
    public  function get_by_roles($url){
    	$mod = $this::where('url',$url)->first();
    	$mod_rol = array();
    	if (!empty($mod)) {
    		$roles_m = DB::table($this->table_pivot)->where('modules_user_id',$mod->id)->get();
    		foreach ($roles_m as $rr) {
	            $rolex = $this->role::find($rr->role_id);
	            $mod_rol[] = (Object)array('name'=>$rolex->name);
        	}
    	}
    	return $mod_rol;
    }

    public function permission_by_roles($id,$url){
    	$all_roles = $this->user::with('roles')->find($id);
        $gr = $this->get_by_roles($url);
        $en = false;
        foreach ($gr as $c) {
            foreach ($all_roles->roles as $al) {
                if ($c->name == $al->name OR strtolower($al->name) == strtolower('master')) {
                    $en = true;
                }
            }
        }
        unset($id,$url,$gr);
        return $en;
    }    

}
