<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Collection;
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable ;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'uid',
        'username',
        'first_name',
        'last_name',
        'phone',
        'email',
        'password',
    ];

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

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

    public function groups()
    {
        return $this->belongsToMany(Group::class);
    }
    public function patches()
    {
        return $this->hasMany(ConfSmartupdate::class , 'uid', 'POWNER');
    }

    public function permissions()
    {
        // Get the permission IDs through the user's groups and roles
        $groupIds = $this->groups()->pluck('groups.id');
        $roleIds = GroupRole::whereIn('group_id', $groupIds)->pluck('role_id');
        $permissionIds = PermissionRole::whereIn('role_id', $roleIds)->pluck('permission_id');

        return Permission::whereIn('id', $permissionIds);
    }

    public function hasPermissions($permissionName)
    {
        return $this->permissions()->where('name', $permissionName)->exists();
    }
}
