<?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;
use Illuminate\Support\Facades\Schema;

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::creating(function ($model) {
            if ($model->isDirty() && !empty(auth()->user()) && Schema::hasColumn($model->getTable(), 'created_by')) {
                $model->created_by = auth()->user()->id;
            }
        });

        static::saving(function ($model) {
            if ($model->isDirty() && !empty(auth()->user()) && Schema::hasColumn($model->getTable(), 'updated_by')) {
                $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()) {
            $excluded_roles_array = auth()->user()->roles()->where('system', true)->pluck('id');
        } else {
//            $excluded_roles_array = ['Superadmin','Admin'];
            $excluded_roles_array = Role::where('system', true)->pluck('id');
        }

        return User::whereDoesntHave('roles', function ($q) use ($excluded_roles_array) {
            $q->whereIn('id', $excluded_roles_array);
        });
    }


//    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);
    }
}
