<?php

namespace App\Models;

use CodeIgniter\Model;

class RoleModel extends Model
{
    protected $table = 'roles';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'slug', 'description', 'created_at', 'updated_at'];
    protected $useTimestamps = true;

    public function getPermissions(int $roleId): array
    {
        return $this->db->table('permissions')
            ->select('permissions.*')
            ->join('role_permissions', 'role_permissions.permission_id = permissions.id')
            ->where('role_permissions.role_id', $roleId)
            ->get()
            ->getResultArray();
    }

    public function assignPermissions(int $roleId, array $permissionIds): void
    {
        $this->db->table('role_permissions')->where('role_id', $roleId)->delete();

        $data = [];
        foreach ($permissionIds as $permissionId) {
            $data[] = [
                'role_id'       => $roleId,
                'permission_id' => $permissionId,
            ];
        }

        if (! empty($data)) {
            $this->db->table('role_permissions')->insertBatch($data);
        }
    }
}
