<?php
/**
 * CustomerWinBackTrigger — runs daily to find customers who haven't
 * ordered in a configurable number of days.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

defined( 'ABSPATH' ) || exit;

class CustomerWinBackTrigger extends AbstractTrigger {

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

	public function get_label(): string {
		return __( 'Customer Win-Back', 'cartcue-sales-automation' );
	}

	public function get_description(): string {
		return __( 'Fires daily for registered customers who have not ordered within the specified number of days.', 'cartcue-sales-automation' );
	}
	public function get_sentence(): string {
		return __( 'a customer hasn\'t ordered in a while', 'cartcue-sales-automation' );
	}

	public function get_test_data(): array {
		$users = get_users( [ 'role' => 'customer', 'number' => 1, 'orderby' => 'registered', 'order' => 'DESC' ] );
		$email = ! empty( $users ) ? $users[0]->user_email : get_option( 'admin_email', '' );
		return [ 'trigger' => $this->get_slug(), 'customer_id' => ! empty( $users ) ? (int) $users[0]->ID : 0, 'customer_email' => $email, 'days_inactive' => 30, '_is_test' => true ];
	}

	public function get_settings_fields(): array {
		return [
			[
				'key'     => 'days_inactive',
				'label'   => __( 'Days since last order', 'cartcue-sales-automation' ),
				'type'    => 'number',
				'default' => 30,
			],
			[
				'key'     => 'min_order_count',
				'label'   => __( 'Minimum previous orders required', 'cartcue-sales-automation' ),
				'type'    => 'number',
				'default' => 1,
			],
		];
	}

	public function register_hooks(): void {
		// No real-time hooks needed — fired by the daily AS action via Plugin::process_win_back().
	}

	/**
	 * Called once per day by Action Scheduler.
	 * Iterates active win-back workflows and finds qualifying customers.
	 */
	public function process_win_back_customers(): void {
		$workflows = $this->plugin->runner->get_active_workflows_for_trigger( $this->get_slug() );
		if ( empty( $workflows ) ) {
			return;
		}

		foreach ( $workflows as $workflow ) {
			$days_inactive   = max( 1, (int) ( $workflow['trigger_settings']['days_inactive']  ?? 30 ) );
			$min_order_count = max( 1, (int) ( $workflow['trigger_settings']['min_order_count'] ?? 1 ) );

			$customers = $this->get_lapsed_customers( $days_inactive, $min_order_count );

			foreach ( $customers as $customer ) {
				$data = [
					'trigger'        => $this->get_slug(),
					'customer_id'    => (int) $customer->ID,
					'customer_email' => $customer->user_email,
					'days_inactive'  => $days_inactive,
				];

				$this->plugin->runner->trigger( (int) $workflow['id'], $data );
			}
		}
	}

	// -------------------------------------------------------------------------
	// Query helpers
	// -------------------------------------------------------------------------

	/**
	 * Find registered customers whose last completed order was exactly
	 * $days_inactive days ago (within a 24-hour window).
	 *
	 * Using wc_get_orders() + WP_User_Query to stay compatible with HPOS.
	 *
	 * @param int $days_inactive
	 * @param int $min_order_count
	 * @return \WP_User[]
	 */
	private function get_lapsed_customers( int $days_inactive, int $min_order_count ): array {
		// Date window: orders completed exactly N days ago (±12 hours).
		$date_before = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days_inactive} days +12 hours" ) );
		$date_after  = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days_inactive} days -12 hours" ) );

		$orders = wc_get_orders( [
			'status'       => [ 'wc-completed', 'wc-processing' ],
			'date_created' => $date_after . '...' . $date_before,
			'limit'        => 500,
			'return'       => 'ids',
			'customer_id'  => [ '>' => 0 ], // registered users only
		] );

		if ( empty( $orders ) ) {
			return [];
		}

		// Collect unique customer IDs.
		$customer_ids = [];
		foreach ( $orders as $order_id ) {
			$order = wc_get_order( $order_id );
			if ( $order && $order->get_customer_id() ) {
				$customer_ids[] = (int) $order->get_customer_id();
			}
		}

		$customer_ids = array_unique( $customer_ids );
		if ( empty( $customer_ids ) ) {
			return [];
		}

		// Filter to customers that haven't ordered more recently.
		$qualifying = [];
		foreach ( $customer_ids as $cid ) {
			$recent_orders = wc_get_orders( [
				'status'      => [ 'wc-completed', 'wc-processing' ],
				'customer_id' => $cid,
				'date_created' => '>' . $date_before,
				'limit'       => 1,
				'return'      => 'ids',
			] );

			if ( ! empty( $recent_orders ) ) {
				continue; // Has ordered more recently — skip.
			}

			// Check total order count.
			$total_orders = wc_get_customer_order_count( $cid );
			if ( $total_orders < $min_order_count ) {
				continue;
			}

			$user = get_user_by( 'id', $cid );
			if ( $user ) {
				$qualifying[] = $user;
			}
		}

		return $qualifying;
	}
}
