<?php
/**
 * Shared order line-item matching for product / category / tag purchase triggers.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class OrderLineMatch {

	/**
	 * @param int    $order_id Order ID.
	 * @param string $type     product|category|tag
	 * @param string $value    Product ID, category slug/ID, or tag slug.
	 */
	public static function order_matches( int $order_id, string $type, string $value ): bool {
		if ( ! $order_id || '' === $value ) {
			return false;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return false;
		}

		foreach ( $order->get_items() as $item ) {
			if ( ! $item instanceof \WC_Order_Item_Product ) {
				continue;
			}
			$product_id   = (int) $item->get_product_id();
			$variation_id = (int) $item->get_variation_id();
			$product      = $item->get_product();
			if ( ! $product ) {
				continue;
			}

			switch ( $type ) {
				case 'product':
					$needle = (int) $value;
					if ( $product_id === $needle || $variation_id === $needle ) {
						return true;
					}
					break;
				case 'category':
					if ( self::product_in_term( $product_id, 'product_cat', $value ) ) {
						return true;
					}
					break;
				case 'tag':
					if ( self::product_in_term( $product_id, 'product_tag', $value ) ) {
						return true;
					}
					break;
			}
		}

		return false;
	}

	private static function product_in_term( int $product_id, string $taxonomy, string $value ): bool {
		if ( is_numeric( $value ) ) {
			return has_term( (int) $value, $taxonomy, $product_id );
		}
		return has_term( sanitize_title( $value ), $taxonomy, $product_id );
	}
}
