<?php

namespace App\Models;

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

    protected $allowedFields = ['uuid', 'church_id', 'name', 'description'];

    protected $useSoftDeletes = false;

    public function getRolesWithPermissions(int $churchId): array
    {
        $db    = \Config\Database::connect();
        $roles = $this->where('church_id', $churchId)->findAll();

        $permModel = new PermissionModel();
        $rpModel   = new RolePermissionModel();

        foreach ($roles as &$role) {
            $permIds = $rpModel->where('role_id', $role['id'])->findAll();
            $ids     = array_column($permIds, 'permission_id');
            $role['permissions'] = $ids ? $permModel->whereIn('id', $ids)->findAll() : [];
        }

        return $roles;
    }
}
