<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Permission;
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Group extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'groups';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'description'];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['users', 'permissions'];

    /**
     * Get the group's users.
     *
     * @return collection
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * Get the group's permissions.
     *
     * @return collection
     */
    public function permissions(): BelongsToMany
    {
        return $this->belongsToMany(Permission::class, 'group_permissions');
    }

    /**
     * Gets only the id of the users.
     *
     * @return array
     */
    public function getUsersAttribute()
    {
        return $this->users()->pluck('id');
    }

    /**
     *	Get a collection of permissions associated with this group
     *	that only contains their primary key, in our case the id.
     *
     *	@return \Illuminate\Support\Collection
     */
    public function getPermissionsAttribute()
    {
        return $this->permissions()->pluck('id');
    }
}
