<?php

namespace Ignite\Core\Entities;

/**
 * Ignite\Core\Entities\GroupPermission
 *
 * @property int $id
 * @property int $group_id
 * @property int $permission_id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Ignite\Core\Entities\Group $group
 * @property-read \Ignite\Core\Collections\PermissionsCollection|\Ignite\Core\Entities\Permission[] $permissions
 * @property-read int|null $permissions_count
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission query()
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission whereGroupId($value)
 * @method static Builder|Base whereHasPermission(string $permission, ?\Ignite\Core\Entities\User $user = null)
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission wherePermissionId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GroupPermission whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class GroupPermission extends Base
{
    /**
     * The custom table name.
     * @var string
     */
    protected $table = 'core_group_permission';

    /**
     * Eloquent event listeners.
     */
    public static function boot()
    {
        parent::boot();

        static::saved(function () {
            app('authorization')->forgetPermissions()->registerPermissions();
        });
    }

    /**
     * The relationship to the group the permission belongs.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function group()
    {
        return $this->belongsTo(Group::class, 'id', 'group_id');
    }

    /**
     * The relationship to the permissions saved for this permission group.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function permissions()
    {
        return $this->hasMany(Permission::class, 'id', 'permission_id');
    }
}
