<?php

namespace Mtc\Core\Admin;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'admin_roles';

    /**
     * @var string[] $fillable attributes that can be auto-filled
     */
    protected $fillable = [
        'name'
    ];

    /**
     * Relationship to a permission
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function permissions()
    {
        return $this->hasMany(RolePermission::class, 'role_id');
    }

    /**
     * Check if role has selected permission
     *
     * @param int $permission_id Permission to check
     * @return bool whether this role has the given permission
     */
    public function hasPermission($permission_id = null)
    {
        return $this->permissions->where('permission_id', $permission_id)->count() > 0;
    }

    /**
     * Assign permissions to a role
     *
     * @param array $permissions
     */
    public function assign($permissions = [])
    {
        // Remove Roles that are no longer needed
        RolePermission::where('role_id', $this->id)
            ->whereNotIn('permission_id', $permissions)
            ->delete();

        // Loop through roles and make sure we have all of them set up
        foreach ($permissions as $permission) {
            RolePermission::firstOrCreate([
                'role_id' => $this->id,
                'permission_id' => $permission
            ]);
        }
    }

}
