<?php
/**
 * CustomerLastOrderDaysRule — passes based on days since the customer's last order.
 *
 * @package CartCue\Rules
 */

namespace CartCue\Rules;

defined( 'ABSPATH' ) || exit;

class CustomerLastOrderDaysRule extends AbstractRule {

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

	public function get_label(): string {
		return __( 'Days Since Last Order', '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 ) {
			return false;
		}

		$last_order = wc_get_customer_last_order( $customer_id );
		if ( ! $last_order ) {
			$days = PHP_INT_MAX;
		} else {
			$date = $last_order->get_date_created();
			$days = $date ? (int) floor( ( time() - $date->getTimestamp() ) / DAY_IN_SECONDS ) : PHP_INT_MAX;
		}

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

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