<?php

namespace Limb_Chatbot\Includes\Data_Objects;

class Wp_Term_Object_Group extends Wp_Object_Group {
	/**
	 * Retrieve all the term groups
	 *
	 * @return array
	 */
	public static function all(): array {
		$term_objects = [];
		$added_taxonomies = [];

		foreach ( parent::get_post_types() as $post_type_key => $post_type_obj ) {
			$post_taxonomies = get_object_taxonomies( $post_type_key, 'objects' );
			foreach ( $post_taxonomies as $taxonomy ) {
				// Skip if already added
				if ( in_array( $taxonomy->name, $added_taxonomies, true ) ) {
					continue;
				}

				// Only include public taxonomies
				if ( ! $taxonomy->public ) {
					continue;
				}

				// Check if taxonomy has terms
				$term_count = wp_count_terms( [
					'taxonomy'   => $taxonomy->name,
					'hide_empty' => false,
				] );

				// Skip if no terms or error
				if ( is_wp_error( $term_count ) || $term_count === 0 ) {
					continue;
				}

				$term_objects[] = self::make( [
					'name'  => 'taxonomy_' . $taxonomy->name,
					'label' => $taxonomy->label,
				] );

				$added_taxonomies[] = $taxonomy->name;
			}
		}

		return $term_objects;
	}
}