<?php

namespace Sartoric\ModularCms\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;
//    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
// DA USARE IN CASO DI AUTO REGISTRAZIONE UTENTE
//    protected $fillable = [
//        'username', 'fullname', 'email', 'password', 'tnc'
//    ];

    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            if ($model->isDirty() && auth()->check()) {
                $model->updated_by = auth()->user()->id;
            }
        });
    }

    public function isSuperAdmin()
    {
        return $this->roles->contains('name', 'Superadmin');
    }

    /**
     * @param array|string $permission
     * @return bool
     */
    public function hasPermission($permission)
    {
        $userPermissions = $this->permissions();
        if (is_array($permission)) {
            foreach ($permission as $item) {
                if (!$userPermissions->contains('name', $item)) {
                    return false;
                }
            }
            return true;
        } else {
            return $userPermissions->contains('name', $permission);
        }
    }

    public static function appusers()
    {
        if (auth()->user()->isSuperAdmin()) {
            $roles_array = ['Superadmin'];
        } else {
            $roles_array = ['Superadmin','Admin'];
        }

        return User::whereDoesntHave('roles', function ($q) use ($roles_array) {
            $q->whereIn('name', $roles_array);
        })->paginate(20);
    }


//    MUTATORS

    /**
     * Hash password
     * @param $input
     */
    public function setPasswordAttribute($input)
    {
        if ($input) {
            $this->attributes['password'] = app('hash')->needsRehash($input) ? Hash::make($input) : $input;
        }
    }


//    RELATIONSHIP

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'sys_role_user');
    }

    public function settings()
    {
        return $this->hasMany(Setting::class);
    }

    public function menuitems()
    {
        $menuitems=collect([]);
        foreach ($this->roles as $role) {
            $menuitems = $menuitems->merge($role->menuitems);
        }
        return $menuitems;
    }

    public function permissions()
    {
        $permissions = collect([]);
        foreach ($this->roles as $role) {
            $permissions = $permissions->merge($role->permissions);
        }
        return $permissions;
    }

    public function resolveChildRouteBinding($childType, $value, $field)
    {
        return parent::resolveChildRouteBinding($childType, $value, $field);
    }
}
