<?php


namespace WDevs\CustomerOrderExport\ColumnCategories;


class ProductTaxonomy extends ColumnCategoryProcessor implements ColumnCategoryInterface {

	public static $category_id = 'product_taxonomies';

	public function __construct( $order_item, $column_id, $column_data ) {
		parent::__construct( $order_item, $column_id, $column_data );
	}

	/**
	 * @param array $excluded_keys
	 *
	 * @return array $fields The fields that can be selected as column
	 * @since 1.0.0
	 */
	public static function get_fields( $excluded_keys = [] ) {
		$fields             = [];
		$product_taxonomies = get_object_taxonomies( 'product', 'objects' );

		if ( $product_taxonomies ) {
			foreach ( $product_taxonomies as $taxonomy ) {
				if ( in_array( $taxonomy->name, $excluded_keys, true ) ) {
					continue;
				}

				$fields[ $taxonomy->name ] = [
					'field'       => $taxonomy->label,
					'name'        => $taxonomy->label,
					'category'    => self::$category_id,
					'description' => $taxonomy->description,
				];
			}
		}

		return $fields;
	}

	/**
	 * @return string $name returns the name of the category
	 * @since 1.0.0
	 */
	public static function get_category_name() {
		return __( 'Product taxonomies', 'orderbridge-for-woocommerce' );
	}

	/**
	 * Returns the value for the current column
	 *
	 * @return null|string
	 * @since 1.0.0
	 */
	public function get_column_value() {
		$value   = null;
		if(!$this->order_item_is_set()){
			return $value;
		}

		$product = $this->order_item->get_product();
		if ( $product ) {
			$value = $this->get_product_taxonomies_value( $product, $this->column_id );
			if ( ! $value && $product->is_type( 'variation' ) ) {
				$parent_product = wc_get_product( $product->get_parent_id() );
				$value          = $this->get_product_taxonomies_value( $parent_product, $this->column_id );
			}
		}

		return $value;
	}

	/**
	 * Retrieves and formats taxonomy terms for a product
	 *
	 * @param \WC_Product $product The WooCommerce product object
	 * @param string $taxonomy_name The taxonomy name to retrieve terms from
	 * @return string|null Comma-separated list of term names or null if:
	 *                     - Taxonomy doesn't exist
	 *                     - Product is invalid
	 *                     - No terms found
	 *                     - Error occurs while retrieving terms
	 * @since 1.0.0
	 */
	private function get_product_taxonomies_value( $product, $taxonomy_name ) {
		if ( ! taxonomy_exists( $taxonomy_name ) ) {
			return null;
		}

		if ( ! $product ) {
			return null;
		}

		$terms = get_the_terms( $product->get_id(), $taxonomy_name );

		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return null;
		}

		$term_names = wp_list_pluck( $terms, 'name' );

		return implode( ', ', $term_names );
	}

}