<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements HasLocalePreference
{
    use HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'admin_id',
        'office_id',
        'locale',
        'phone',
        'image',
        'status',
        'is_admin'
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function admin()
    {
        return $this->belongsTo(User::class);
    }

    public function account()
    {
        return $this->hasOne(Account::class);
    }

    public function office()
    {
        return $this->belongsTo(Office::class);
    }

    public function subAccount()
    {
        return $this->belongsTo(SubAccount::class);
    }


    function getPublicImageAttribute(){
        return $this->image? 'uploads/'.$this->image: null;
    }

    function isofficeManager()
    {
        return $this->hasRole('office manager') ? true : false;
    }

    function isAdmin()
    {
        return $this->is_admin;
    }

    function isSuperAdmin()
    {
        return $this->id==1;
    }

    public function countEmployers()
    {
        if ($this->is_admin) {
            return -1;
        } else {
            return  User::where('admin_id', $this->id)->count();
        }
    }

    /**
     * Get the user's preferred locale.
     *
     * @return string
     */
    public function preferredLocale()
    {
        return $this->locale;
    }

    public function receivesBroadcastNotificationsOn()
    {
        return 'users.'.$this->id;
    }

}
