<?php
/**
 * OrderContainsCategoryRule — order includes a product in a category.
 *
 * @package CartCue\Rules
 */

namespace CartCue\Rules;

defined( 'ABSPATH' ) || exit;

class OrderContainsCategoryRule extends AbstractRule {

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

	public function get_label(): string {
		return __( 'Order Contains Category', '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 'select';
	}

	public function get_value_options(): array {
		$options = [];
		$terms   = get_terms(
			[
				'taxonomy'   => 'product_cat',
				'hide_empty' => false,
			]
		);
		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return $options;
		}
		foreach ( $terms as $term ) {
			$options[ (string) $term->term_id ] = $term->name;
		}
		return $options;
	}

	public function evaluate( array $config, array $data ): bool {
		$order_id    = (int) ( $data['order_id'] ?? 0 );
		$category_id = (int) ( $config['value'] ?? 0 );
		if ( ! $order_id || ! $category_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;
			}
			$product_id = (int) $item->get_product_id();
			if ( ! $product_id ) {
				continue;
			}
			if ( has_term( $category_id, 'product_cat', $product_id ) ) {
				$found = true;
				break;
			}
		}

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