<?php
/**
 * OrderContainsProductRule — order line items include a product ID.
 *
 * @package CartCue\Rules
 */

namespace CartCue\Rules;

defined( 'ABSPATH' ) || exit;

class OrderContainsProductRule extends AbstractRule {

	public function get_slug(): string {
		return 'order_contains_product';
	}

	public function get_label(): string {
		return __( 'Order Contains Product', 'cartcue-sales-automation' );
	}

	public function get_operators(): array {
		return [
			'includes'     => __( 'includes', 'cartcue-sales-automation' ),
			'not_includes' => __( 'does not include', 'cartcue-sales-automation' ),
		];
	}

	public function get_value_type(): string {
		return 'async_select';
	}

	public function get_value_source(): string {
		return 'products';
	}

	public function get_value_placeholder(): string {
		return __( 'Search products', 'cartcue-sales-automation' );
	}

	public function evaluate( array $config, array $data ): bool {
		$order_id   = (int) ( $data['order_id'] ?? 0 );
		$product_id = (int) ( $config['value'] ?? 0 );
		if ( ! $order_id || ! $product_id ) {
			return true;
		}

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

		$found = false;
		foreach ( $order->get_items() as $item ) {
			if ( ! $item instanceof \WC_Order_Item_Product ) {
				continue;
			}
			if ( (int) $item->get_product_id() === $product_id || (int) $item->get_variation_id() === $product_id ) {
				$found = true;
				break;
			}
		}

		$operator = sanitize_key( $config['operator'] ?? 'includes' );
		return 'not_includes' === $operator ? ! $found : $found;
	}
}
