<?php
/**
 * OrderStatusChangedTrigger — fires when an order transitions between statuses.
 *
 * @package CartCue\Triggers
 */

namespace CartCue\Triggers;

defined( 'ABSPATH' ) || exit;

class OrderStatusChangedTrigger extends AbstractTrigger {

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

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

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

	public function get_description(): string {
		return __( 'An order moves from one status to another.', 'cartcue-sales-automation' );
	}

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

	public function get_settings_fields(): array {
		$statuses = [ '' => __( 'Any status', 'cartcue-sales-automation' ) ];
		foreach ( wc_get_order_statuses() as $slug => $label ) {
			$statuses[ ltrim( $slug, 'wc-' ) ] = $label;
		}

		return [
			[
				'key'     => 'from_status',
				'label'   => __( 'From status', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => '',
				'options' => $statuses,
			],
			[
				'key'     => 'to_status',
				'label'   => __( 'To status', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => '',
				'options' => $statuses,
			],
		];
	}

	public function is_still_valid( array $data ): bool {
		$order_id = (int) ( $data['order_id'] ?? 0 );
		$to       = sanitize_key( $data['to_status'] ?? '' );
		if ( ! $order_id || ! $to ) {
			return false;
		}
		$order = wc_get_order( $order_id );
		return $order && $order->get_status() === $to;
	}

	public function get_test_data(): array {
		return [
			'trigger'        => $this->get_slug(),
			'order_id'       => 0,
			'from_status'    => 'pending',
			'to_status'      => 'processing',
			'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_changed', [ $this, 'handle' ], 10, 4 );
	}

	/**
	 * @param int       $order_id Order ID.
	 * @param string    $from     Previous status (no wc- prefix).
	 * @param string    $to       New status.
	 * @param \WC_Order $order    Order object.
	 */
	public function handle( int $order_id, string $from, string $to, $order ): void {
		if ( ! $order instanceof \WC_Order ) {
			$order = wc_get_order( $order_id );
		}
		if ( ! $order ) {
			return;
		}

		$from = 0 === strpos( $from, 'wc-' ) ? substr( $from, 3 ) : $from;
		$to   = 0 === strpos( $to, 'wc-' ) ? substr( $to, 3 ) : $to;

		$data = [
			'trigger'        => $this->get_slug(),
			'order_id'       => $order_id,
			'from_status'    => $from,
			'to_status'      => $to,
			'customer_id'    => (int) $order->get_customer_id(),
			'customer_email' => $order->get_billing_email(),
		];

		foreach ( $this->plugin->runner->get_active_workflows_for_trigger( $this->get_slug() ) as $workflow ) {
			$settings = $workflow['trigger_settings'] ?? [];
			$from_want = sanitize_key( $settings['from_status'] ?? '' );
			$to_want   = sanitize_key( $settings['to_status'] ?? '' );

			if ( $from_want && $from_want !== $from ) {
				continue;
			}
			if ( $to_want && $to_want !== $to ) {
				continue;
			}

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