<?php
/**
 * Computes a customer's WooCommerce lifetime statistics.
 *
 * Shared by the free order-note summary and the Pro customer-intelligence
 * enrichment so both read the same numbers from a single source of truth.
 *
 * @package WooAttioSync
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

/**
 * Lifetime-value statistics for a WooCommerce customer, derived from their paid
 * orders (processing + completed).
 */
final class WooAttioSync_Customer_Stats {

	/** Cap the history scan so one customer never triggers an unbounded query. */
	private const MAX_ORDERS = 500;

	/**
	 * Compute lifetime stats for the customer behind an email address.
	 *
	 * @param string $email Billing email to aggregate paid orders for.
	 * @return array{count:int,total:float,average:float,first_date:string,last_date:string}
	 *         Zeroed/empty when the customer has no paid orders or WooCommerce is absent.
	 */
	public static function for_email( string $email ): array {
		$empty = array(
			'count'      => 0,
			'total'      => 0.0,
			'average'    => 0.0,
			'first_date' => '',
			'last_date'  => '',
		);

		if ( '' === $email || ! function_exists( 'wc_get_orders' ) ) {
			return $empty;
		}

		$orders = wc_get_orders(
			array(
				'customer' => $email,
				'status'   => array( 'wc-processing', 'wc-completed' ),
				'limit'    => self::MAX_ORDERS,
				'orderby'  => 'date',
				'order'    => 'ASC',
				'return'   => 'objects',
			)
		);

		$count = is_array( $orders ) ? count( $orders ) : 0;
		if ( 0 === $count ) {
			return $empty;
		}

		$total = 0.0;
		foreach ( $orders as $order ) {
			$total += (float) $order->get_total();
		}

		$first = $orders[0]->get_date_created();
		$last  = $orders[ $count - 1 ]->get_date_created();

		return array(
			'count'      => $count,
			'total'      => $total,
			'average'    => $total / $count,
			'first_date' => $first ? $first->date_i18n( 'Y-m-d' ) : '',
			'last_date'  => $last ? $last->date_i18n( 'Y-m-d' ) : '',
		);
	}
}
