<?php
/**
 * OrderPaidTrigger — fires when an order payment is confirmed.
 *
 * v1.3: HPOS-compatible dedup flag, get_sentence(), get_test_data(),
 *       is_still_valid() deferred recheck.
 *
 * @package CartCue
 */

namespace CartCue\Triggers;

defined( 'ABSPATH' ) || exit;

class OrderPaidTrigger extends AbstractTrigger {

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

	public function get_label(): string {
		return __( 'Order Paid', 'cartcue-sales-automation' );
	}

	public function get_sentence(): string {
		return __( 'a customer pays for an order', 'cartcue-sales-automation' );
	}

	public function get_description(): string {
		return __( 'A customer successfully pays for an order.', 'cartcue-sales-automation' );
	}

	public function supports_recheck(): bool {
		return true;
	}

	/**
	 * DeferredStateCheck: verify the order is still in a paid/complete state
	 * before a delayed play fires (e.g. a review-request email sent 3 days later).
	 */
	public function is_still_valid( array $data ): bool {
		$order_id = (int) ( $data['order_id'] ?? 0 );
		if ( ! $order_id ) {
			return false;
		}
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return false;
		}
		$paid_statuses = [ 'processing', 'completed', 'on-hold' ];
		return in_array( $order->get_status(), $paid_statuses, true );
	}

	public function get_test_data(): array {
		return [
			'trigger'        => $this->get_slug(),
			'order_id'       => 0,
			'customer_id'    => get_current_user_id(),
			'customer_email' => get_option( 'admin_email', '' ),
			'_is_test'       => true,
		];
	}

	public function register_hooks(): void {
		add_action( 'woocommerce_payment_complete',        [ $this, 'handle' ], 10, 1 );
		add_action( 'woocommerce_order_status_processing', [ $this, 'handle' ], 10, 1 );
		add_action( 'woocommerce_order_status_completed',  [ $this, 'handle' ], 10, 1 );
	}

	public function handle( int $order_id ): void {
		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			return;
		}

		// HPOS-compatible dedup flag.
		if ( $order->get_meta( '_ap_order_paid_fired' ) ) {
			return;
		}
		$order->update_meta_data( '_ap_order_paid_fired', '1' );
		$order->save_meta_data();

		$this->fire( [
			'trigger'        => $this->get_slug(),
			'order_id'       => $order_id,
			'customer_id'    => (int) $order->get_customer_id(),
			'customer_email' => $order->get_billing_email(),
		] );
	}
}
