<?php

namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Exceptions\PermissionException;
use Illuminate\Database\Eloquent\Model;

class Domain extends Model
{
    //
    protected $fillable = ['domain'];


    public function users()
    {
        return $this->belongsToMany('App\User')->withTimestamps()->using('App\DomainUser')->withPivot(['role']);
    }

    public function accounts()
    {
        //return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
        return $this->hasMany('App\Account','domain','domain');
    }

    public function aliases()
    {
        //return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
        return $this->hasMany('App\Alias','source_domain','domain');
    }

    public function getRole($rquser=null)
    {
        if(is_numeric($rquser))
        {
            $rqid = $rquser; 
        }
        else if(is_object($rquser) && $rquser instanceof \App\User)
        {
            $rqid = $rquser->id;
        }
        else
        {
            $rqid=Auth::User()->id;
        }

        foreach($this->users as $user)
        {
            if($user->id == $rqid)
            {
                return $user->pivot->role;
            }
        }
        return null;
    }

    public function hasRole($rqrole,$rquser=null)
    {
        $role = $this->getRole($rquser);

        if($rqrole == 'own')
        {
            $validroles = ['own'];
        }
        else if($rqrole == 'edit')
        {
            $validroles = ['own','edit'];
        }
        else if($rqrole == 'view')
        {
            $validroles = ['own','edit','view'];
        }

        return in_array($role,$validroles);
    }

    public function needRole($rqrole,$rquser=null)
    {
        if(!($this->hasRole($rqrole,$rquser)))
        {
            throw new PermissionException($rqrole);
        }
    }


}
