<?php

namespace App\Models;

use App\Notifications\ResetBackendUserPassword;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;

class BackendUser extends Model implements
    AuthenticatableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;
    use SoftDeletes;
    use Notifiable;

    protected $hidden = ['password', 'remember_token'];
    protected $guarded = ['id'];
    protected $guard = 'admin';

    public function backendRole()
    {
        return $this->belongsTo(BackendRole::class);
    }

    public function websites()
    {
        return $this->belongsToMany(Website::class)->withPivot("is_default")->withTimestamps();
    }

    public function hasRole(array $roles)
    {
        $user_role = $this->backendRole->name;

        return in_array($user_role, $roles);
    }

    public function hasPermission($permissionName)
    {
        $permissions = $this->backendRole->permissions->filter(function ($permission) use ($permissionName) {
            return $permission->name == $permissionName;
        });

        return $permissions->isEmpty();
    }

    public function setUsernameAttribute($username)
    {
        $this->attributes["username"] = strtolower($username);
    }

    public function setPasswordAttribute($password)
    {
        $this->attributes["password"] = Hash::make($password);
    }

    public function getDefaultWebsite()
    {
        $websites = $this->websites;
        $website = $websites->filter(function ($websiteData) {
            return $websiteData->pivot->is_default == 1;
        })->first();
        return $website;
    }

    public function hasWebsite($websiteId)
    {
        $websites = $this->websites;
        $website = $this->websites->find($websiteId);
        return !empty($website);
    }

    /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetBackendUserPassword($token, $this));
    }

    /**
     * Get the e-mail address where password reset links are sent.
     *
     * @return string
     */
    public function getEmailForPasswordReset()
    {
        return $this->email;
    }
}
