<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
 * W2PShop Woo Util Main Class
 *
 */
defined( 'ABSPATH' ) || exit;

final class W2PShopWooUtil {

	public static function get_woocommerce_cart_data( string $cart_item_key, $data_name = '' ) {
		if ( empty( $cart_item_key ) ) {
			return null;
		}

		// Get current cart of user.
		global $woocommerce;
		$cart = $woocommerce->cart->get_cart();
		if ( ! array_key_exists( $cart_item_key, $cart ) || ! array_key_exists( 'w2pshop_product', $cart[ $cart_item_key ] )) {
			return null;
		}
		$w2pshop_product = json_decode( html_entity_decode( $cart[ $cart_item_key ]['w2pshop_product'] ), true );

		// By default return full w2pshop_product data if no data_name is given. 2025-12-31 minor change of check to avoid rare edge case behavior of empty().
		if ( '' === $data_name ) {
			return $w2pshop_product;
		}

		// Return product data value (if exists).
		return W2PShopSettings::get_product_data_value( $w2pshop_product, $data_name );
	}

	public static function set_order_item_meta( $order_item_id, $item_data ) : void {
		try {
			wc_update_order_item_meta( $order_item_id, '_w2pshop_product', $item_data );
		} catch ( Exception $e ) {
			//error_log( $e->getMessage() ); //failing quietly for now due to plugin-check requirements
		}
	}

}//!W2PShopWooUtil
