<?php


namespace WDevs\CustomerOrderExport\ColumnCategories;


class GlobalProductAttribute extends ColumnCategoryProcessor implements ColumnCategoryInterface {

	public static $category_id = 'global_product_attributes';

	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               = [];
		$attribute_taxonomies = wc_get_attribute_taxonomies();

		if ( $attribute_taxonomies ) {
			foreach ( $attribute_taxonomies as $tax ) {
				$name                           = $tax->attribute_label;
				$fields[ $tax->attribute_name ] = [
					'field' => $name,
					'name'  => $name,
					'category'    => self::$category_id,
					//'description' => sprintf(__('Product attribute: %s', 'orderbridge-for-woocommerce'), $tax->attribute_label),
				];
			}
		}

		return $fields;
	}

	/**
	 * @return string $name returns the name of the category
	 * @since 1.0.0
	 */
	public static function get_category_name() {
		return __( 'Product attributes', '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_global_product_attribute_value( $product, $this->column_id );
			if ( ! $value && $product->is_type( 'variation' ) ) {
				$parent_product = wc_get_product( $product->get_parent_id() );
				$value          = $this->get_global_product_attribute_value( $parent_product, $this->column_id );
			}
		}

		return $value;
	}

	/**
	 * Gets the value of a global product attribute
	 *
	 * @param \WC_Product $product The product object
	 * @param string $attribute The attribute name
	 * @return string|null The attribute value or null if not available
	 *
	 * @since 1.0.0
	 */
	protected function get_global_product_attribute_value( $product, $attribute ) {
		return $product->get_attribute( $attribute );
	}

}