protected function getCountQuery(): Select
    {
        if ($this->countQuery instanceof Select) {
            return $this->countQuery;
        }

        if ($this->searchTerm !== null && $this->searchFields === null) {
            $fields = $this->getFields();
            $searchFields = [];
            foreach ($fields as $field) {
                $searchFields[] = $field['name'];
            }
        } else {
            $searchFields = null;
        }

        $query = clone $this;
        $query->resetFields();
        $query->resetLimit();
        $query->resetOrderBy();
        $query->field('COUNT(*)', 'total');

        if ($this->resetGroupBy) {
            $query->resetGroupBy();
        }

        if ($searchFields !== null) {
            $query->setSearchFields($searchFields);
        }

        return $query;
    }