<?php
/**
 * OrderPaymentMethodRule — matches WooCommerce payment method ID.
 *
 * @package CartCue\Rules
 */

namespace CartCue\Rules;

defined( 'ABSPATH' ) || exit;

class OrderPaymentMethodRule extends AbstractRule {

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

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

	public function get_operators(): array {
		return [
			'equals'   => __( 'payment method is', 'cartcue-sales-automation' ),
			'is_not'   => __( 'payment method is not', 'cartcue-sales-automation' ),
			'contains' => __( 'payment method ID contains', 'cartcue-sales-automation' ),
		];
	}

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

	public function get_value_options(): array {
		$options = [];
		if ( ! function_exists( 'WC' ) ) {
			return $options;
		}
		foreach ( WC()->payment_gateways()->payment_gateways() as $gateway ) {
			$options[ $gateway->id ] = $gateway->get_title();
		}
		return $options;
	}

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

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

		$method  = (string) $order->get_payment_method();
		$expect  = sanitize_text_field( $config['value'] ?? '' );
		$op      = $config['operator'] ?? 'equals';

		if ( 'is_not' === $op ) {
			return $method !== $expect;
		}
		if ( 'contains' === $op ) {
			return false !== stripos( $method, $expect );
		}
		return $method === $expect;
	}
}
