<?php

namespace App\Models\Backoffice\Auth;

use App\Models\Backoffice\Support\BaseModel;
use App\Notifications\Backoffice\ResetBackendUserPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Auth\Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;

class BackendUser extends BaseModel implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable;
    use SoftDeletes;
    use Notifiable;

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

    public function permissions()
    {
        return $this->belongsToMany(BackendPermission::class, 'backend_users_permissions');
    }

    public function userType()
    {
        return $this->belongsTo(BackendUserType::class, 'type_id');
    }

    public function hasPermission($permissions)
    {
        if (is_string($permissions)) {
            $permissions = [$permissions];
        }

        $hasPermission = false;

        if (is_array($permissions)) {
            foreach ($permissions as $permission) {
                if (Str::contains($permission, "|")) {
                    $hasPermission = $this->permissions->hasItem("name", explode("|", $permission));
                } else {
                    $hasPermission = $this->permissions->hasItem("name", $permission);
                }

                if (!$hasPermission) {
                    break;
                }
            }

            return $hasPermission;
        } else {
            return false;
        }
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

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

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