<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'address',
        'phone',
        'profile_photo',
        'gender',
        'status',
        'employee_id',
        'device_token'
    ];

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

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

    public static function getPermissionGroup()
    {
        return Permission::select('group_name as name')->groupBy('group_name')->orderBy('id', 'asc')->get();
    }

    public static function getpermissionsByGroupName($group_name)
    {
        return Permission::select('name', 'id', 'group_name')->where('group_name', $group_name)->get();
    }

    public static function roleHasPermissions($role, $permissions): bool
    {
        foreach ($permissions as $permission) {
            if ($role->hasPermissionTo($permission->name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Get the user's roles
     *
     * @return HasMany
     */
    public function user_roles()
    {
        return $this->hasMany(ModelHasRoles::class, 'model_id');
    }

    public function organizations()
    {
        return $this->belongsToMany(Organization::class);
    }

    public function isSuperAdmin()
    {
        return $this->hasRole('super-admin');
    }
}
