<?php

// If this file is called directly, abort.
if (!defined('WPINC')) {
	die;
}

class ProductAttributesController {
	public function getAttributes() {

		// If the woocommerce doesn't exist on the site
		if (!function_exists('wc_get_attribute_taxonomies')) {
			return [];
		}
		// END If the woocommerce doesn't exist on the site

		$attributes = [];
		$globalAttributes = wc_get_attribute_taxonomies();

		if (empty($globalAttributes)) {
			return [];
		}

		$taxonomyList = array_map(function($attr) {
			return wc_attribute_taxonomy_name($attr->attribute_name);
		}, $globalAttributes);

		// Load all terms for all taxonomies in one query
		$allTerms = get_terms([
			'taxonomy' => $taxonomyList,
			'hide_empty' => false,
		]);

		if (is_wp_error($allTerms)) {
			return [];
		}

		$termsByTaxonomy = [];
		foreach ($allTerms as $term) {
			$termsByTaxonomy[$term->taxonomy][] = [
				'value' => (string) $term->term_id,
				'label' => (string) $term->name,
				'hex_code' => "",
			];
		}

		foreach ($globalAttributes as $attr) {
			$taxonomy = wc_attribute_taxonomy_name($attr->attribute_name);

			$attributes[] = [
				'id' => (int) $attr->attribute_id,
				'code' => $attr->attribute_name,
				'options' => $termsByTaxonomy[$taxonomy] ?? [],
			];
		}

		return $attributes;
	}
}