<?php
/**
 * OrderCountRule — passes based on the customer's total order count.
 *
 * @package CartCue\Rules
 */

namespace CartCue\Rules;

defined( 'ABSPATH' ) || exit;

class OrderCountRule extends AbstractRule {

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

	public function get_label(): string {
		return __( 'Customer has placed orders', 'cartcue-sales-automation' );
	}

	public function get_operators(): array {
		return [
			'greater_than' => __( 'is greater than', 'cartcue-sales-automation' ),
			'less_than'    => __( 'is less than', 'cartcue-sales-automation' ),
			'equals'       => __( 'equals', 'cartcue-sales-automation' ),
		];
	}

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

	public function evaluate( array $config, array $data ): bool {
		$customer_id = (int) ( $data['customer_id'] ?? 0 );

		if ( ! $customer_id && ! empty( $data['order_id'] ) ) {
			$order       = wc_get_order( (int) $data['order_id'] );
			$customer_id = $order ? (int) $order->get_customer_id() : 0;
		}

		if ( ! $customer_id ) {
			$count = 0; // Guest.
		} else {
			$count = (int) wc_get_customer_order_count( $customer_id );
		}

		$operator = sanitize_key( $config['operator'] ?? 'greater_than' );
		$expected = (int) ( $config['value'] ?? 1 );

		return $this->compare( $count, $operator, $expected );
	}
}
