<?php
/**
 * OrderCancelledTrigger — fires when an order is cancelled.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

defined( 'ABSPATH' ) || exit;

class OrderCancelledTrigger extends AbstractTrigger {

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

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

	public function get_sentence(): string {
		return __( 'an order is cancelled', 'cartcue-sales-automation' );
	}

	public function get_description(): string {
		return __( 'An order is cancelled.', 'cartcue-sales-automation' );
	}

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

	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 );
		return $order && 'cancelled' === $order->get_status();
	}

	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_order_status_cancelled', [ $this, 'handle' ], 10, 1 );
	}

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

		if ( $order->get_meta( '_ap_order_cancelled_fired' ) ) {
			return;
		}
		$order->update_meta_data( '_ap_order_cancelled_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(),
		] );
	}
}
