<?php
/**
 * IsFirstOrderRule — passes if the current order is (or is not) the customer's first.
 *
 * @package CartCue\Rules
 */

namespace CartCue\Rules;

defined( 'ABSPATH' ) || exit;

class IsFirstOrderRule extends AbstractRule {

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

	public function get_label(): string {
		return __( 'This is the customer’s first order', 'cartcue-sales-automation' );
	}

	public function get_operators(): array {
		return [
			'is'     => __( 'is the customer\'s first order', 'cartcue-sales-automation' ),
			'is_not' => __( 'is NOT the customer\'s first order', 'cartcue-sales-automation' ),
		];
	}

	/** No value field needed — just the operator. */
	public function get_value_type(): string {
		return 'hidden';
	}

	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;
		}

		$customer_id = (int) $order->get_customer_id();
		if ( $customer_id ) {
			$order_count = wc_get_customer_order_count( $customer_id );
			$is_first    = $order_count <= 1;
		} else {
			// Guest: check by email.
			$orders_by_email = wc_get_orders( [
				'billing_email' => $order->get_billing_email(),
				'limit'         => 2,
				'return'        => 'ids',
				'status'        => [ 'wc-completed', 'wc-processing' ],
			] );
			$is_first = count( $orders_by_email ) <= 1;
		}

		$operator = $config['operator'] ?? 'is';
		return 'is_not' === $operator ? ! $is_first : $is_first;
	}
}
