<?php

namespace ShopManagerPro\Taxonomies;

class TaxonomyRepository {
	private static ?DTO\TaxonomyCollection $taxonomies = null;

	public static function getTaxonomies() {
		if (self::$taxonomies) {
			return self::$taxonomies;
		} global $wpdb;
		$query = "
			SELECT
				wp_term_taxonomy.taxonomy AS taxonomy_key ,
				JSON_ARRAYAGG(
					JSON_OBJECT(
						'id', wp_terms.term_id,
						'name', wp_terms.name
					)
				) AS terms
			FROM
				{$wpdb->term_taxonomy} AS wp_term_taxonomy
			LEFT JOIN
				{$wpdb->terms} AS wp_terms ON wp_terms.term_id = wp_term_taxonomy.term_id
			WHERE
				wp_term_taxonomy.term_taxonomy_id IN (
					SELECT
						DISTINCT wp_term_relationships.term_taxonomy_id
					FROM
						{$wpdb->term_relationships} AS wp_term_relationships
					WHERE
						wp_term_relationships.object_id IN (
							SELECT
								wp_posts.id
							FROM
								{$wpdb->posts} AS wp_posts
							WHERE
								wp_posts.post_type = 'product'
						)
				)
			GROUP BY
				wp_term_taxonomy.taxonomy
			ORDER BY
				wp_term_taxonomy.taxonomy
		";
		$taxonomiesByKey = [];
		$taxonomiesByTermId = [];
		$termsByTermId = [];
		foreach ($wpdb->get_results($query, ARRAY_A) as $row) {
			$terms = \ShopManagerPro\Shared\Utils\JSON::decode($row['terms']);
			$termsById = [];
			$taxonomyKey = $row['taxonomy_key'];
			foreach ($terms as $term) {
				$termName = isset($term['name']) ? html_entity_decode($term['name']) : $taxonomyKey;
				$term = new DTO\TaxonomyTerm($term['id'], $termName);
				$termsById[$term->id] = $term;
				$termsByTermId[$term->id] = $term;
			} $taxonomy = new DTO\Taxonomy(key: $taxonomyKey, name: TaxonomyNameService::getTaxonomyName($taxonomyKey), terms: $termsById);
			$taxonomiesByKey[$taxonomyKey] = $taxonomy;
			foreach ($termsById as $term) {
				$taxonomiesByTermId[$term->id] = $taxonomy;
			}
		} self::$taxonomies = new DTO\TaxonomyCollection(taxonomiesByKey: $taxonomiesByKey, taxonomiesByTermId: $taxonomiesByTermId, termsByTermId: $termsByTermId);

		return self::$taxonomies;
	}

	public static function getTermsByID() {
		global $wpdb;
		$query = "
			SELECT
				term_id , name
			FROM
				{$wpdb->terms} AS wp_terms
		";
		$terms = [];
		foreach ($wpdb->get_results($query, ARRAY_A) as $row) {
			$terms[$row['term_id']] = new DTO\TaxonomyTerm(id: $row['term_id'], name: html_entity_decode($row['name']));
		}

return $terms;
	}
}
