<?php

namespace App\Models;

use CodeIgniter\Model;

class RoleModel extends Model
{
    protected $table      = 'roles';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'name',
        'description',
        'is_system'
    ];

    /**
     * Sinkronisasi permission role
     */
    public function syncPermissions(int $roleId, array $permissions)
    {
        $db = db_connect();

        // Hapus permission lama
        $db->table('role_permissions')
           ->where('role_id', $roleId)
           ->delete();

        // Insert permission baru
        foreach ($permissions as $pid) {
            $db->table('role_permissions')->insert([
                'role_id'       => $roleId,
                'permission_id' => $pid
            ]);
        }
    }
}
