<?php


namespace WDevs\CustomerOrderExport\ColumnCategories;


use WDevs\CustomerOrderExport\Column;

class OrderItemmeta extends ColumnCategoryProcessor implements ColumnCategoryInterface {

	public static $category_id = 'order_itemmeta';

	public const CACHE_KEY_ORDER_ITEMMETA = 'wdevs_coe_unique_order_itemmeta_keys';

	public const TRANSIENT_KEY_ORDER_ITEMMETA = 'wc_wdevs_coe_unique_order_itemmeta_keys';

	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        = [];
		$itemmeta_keys = self::get_unique_order_itemmeta_keys( $excluded_keys );

		foreach ( $itemmeta_keys as $key ) {
			$name           = wc_attribute_label( $key );
			$fields[ $key ] = [
				'field'    => $name,
				'name'     => $name,
				'category' => self::$category_id,
				//'description' => sprintf( __( 'Custom order item meta: %s', 'orderbridge-for-woocommerce' ), $key ),
			];
		}

		return $fields;
	}

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

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

		return $this->get_order_itemmeta_value( $this->order_item, $this->column_id );
	}

	/**
	 * Retrieves and formats metadata value from an order item
	 *
	 * @param \WC_Order_Item $order_item The WooCommerce order item object
	 * @param string $meta_key The meta key to retrieve
	 *
	 * @return string|null The formatted meta value or null if empty/not found
	 *                     - Returns comma-separated string for array values
	 *                     - Returns original value for non-array values
	 *                     - Returns null for empty arrays or falsy values
	 * @since 1.0.0
	 */
	private function get_order_itemmeta_value( $order_item, $meta_key ) {
		$value = $order_item->get_meta( $meta_key );

		if ( is_array( $value ) ) {
			if ( empty( $value ) ) {
				return null;
			}

			$value = implode( ', ', $value );
		}

		return $value ?: null;
	}

	/**
	 * Retrieves unique order item meta keys from the database
	 *
	 * @param array $exclude Keys to exclude from results
	 *
	 * @return array Unique meta keys
	 * @since 1.0.0
	 */
	private static function get_unique_order_itemmeta_keys( $exclude = [] ) {
		$cached_result = wp_cache_get( self::CACHE_KEY_ORDER_ITEMMETA, Column::CACHE_GROUP );
		if ( false !== $cached_result ) {
			return $cached_result;
		}

		$meta_keys = get_transient( self::TRANSIENT_KEY_ORDER_ITEMMETA );

		if ( false === $meta_keys ) {
			global $wpdb;

			$sql = "SELECT DISTINCT meta_key 
			FROM {$wpdb->prefix}woocommerce_order_itemmeta 
			WHERE meta_key NOT LIKE ''";

			$hidden_order_itemmeta = apply_filters(
				'wdevs_coe_hidden_order_itemmeta',
				[
					'_qty',
					'_tax_class',
					'_product_id',
					'_variation_id',
					'_line_subtotal',
					'_line_subtotal_tax',
					'_line_total',
					'_line_tax',
					'method_id',
					'instance_id',
					'cost',
					'total_tax',
					'taxes',
					'rate_id',
					'label',
					'compound',
					'tax_amount',
					'shipping_tax_amount',
					'rate_percent',
					'_reduced_stock',
					'_restock_refunded_items',
					'_line_tax_data',
				]
			);

			$excluded_keys = array_unique( array_merge( $hidden_order_itemmeta, (array) $exclude ) );

			if ( ! empty( $excluded_keys ) ) {
				$excluded_keys = array_map( 'sanitize_key', $excluded_keys );

				$placeholders          = array_fill( 0, count( $excluded_keys ), '%s' );
				$imploded_placeholders = implode( ', ', $placeholders );

				$sql .= $wpdb->prepare(
					" AND meta_key NOT IN (" . $imploded_placeholders . ")",
					...$excluded_keys
				);
			}


			$sql .= " ORDER BY meta_key";

			$meta_keys = $wpdb->get_col( $sql );
			$meta_keys = apply_filters( 'wdevs-coe_unique_order_itemmeta_keys', $meta_keys );

			set_transient( self::TRANSIENT_KEY_ORDER_ITEMMETA, $meta_keys );
		}

		wp_cache_set( self::CACHE_KEY_ORDER_ITEMMETA, $meta_keys, Column::CACHE_GROUP );

		return $meta_keys;
	}

}