<?php
/**
 * ChangeOrderStatusAction — changes the status of a WooCommerce order.
 *
 * Common use cases:
 *  - Auto-complete virtual/downloadable product orders on payment
 *  - Auto-cancel on-hold orders after N days of non-payment
 *  - Move orders to processing after a manual approval step
 *  - Flag orders as "on-hold" when fraud conditions are detected
 *
 * If the order is already in the target status, the action is a safe no-op.
 * If there is no order in the trigger context, the action silently skips.
 *
 * @package CartCue
 */

namespace CartCue\Actions;

use CartCue\Context;

defined( 'ABSPATH' ) || exit;

class ChangeOrderStatusAction extends AbstractAction {

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

	public function get_label(): string {
		return __( 'Update order status', 'cartcue-sales-automation' );
	}

	public function get_settings_fields(): array {
		// Build status list from WooCommerce, strip 'wc-' prefix for storage.
		$statuses = [];
		foreach ( wc_get_order_statuses() as $slug => $label ) {
			$statuses[ preg_replace( '/^wc-/', '', (string) $slug ) ] = $label;
		}

		return [
			[
				'key'     => 'new_status',
				'label'   => __( 'Change status to', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => 'completed',
				'options' => $statuses,
			],
			[
				'key'         => 'note',
				'label'       => __( 'Add a note when changing status (optional)', 'cartcue-sales-automation' ),
				'type'        => 'text',
				'default'     => '',
				'placeholder' => __( 'e.g. Auto-completed by CartCue', 'cartcue-sales-automation' ),
			],
		];
	}

	public function run( array $settings, Context $context ): void {
		$data     = $context->all();
		$order_id = (int) ( $data['order_id'] ?? 0 );

		if ( ! $order_id ) {
			// No order in context (e.g. win-back trigger) — skip silently.
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			throw new \RuntimeException(
				'Change order status: order #' . absint( $order_id ) . ' not found.'
			);
		}

		$new_status = sanitize_key( $settings['new_status'] ?? 'completed' );

		// Validate without the wc- prefix.
		$all_valid = array_map( fn( $s ) => preg_replace( '/^wc-/', '', (string) $s ), array_keys( wc_get_order_statuses() ) );
		if ( ! in_array( $new_status, $all_valid, true ) ) {
			throw new \RuntimeException(
				sprintf( 'Change order status: "%s" is not a valid WooCommerce order status.', esc_html( $new_status ) )
			);
		}

		// No-op if already in target status.
		if ( preg_replace( '/^wc-/', '', (string) $order->get_status() ) === $new_status ) {
			return;
		}

		// Skip during test runs — don't actually change real order statuses.
		if ( ! empty( $data['_is_test'] ) ) {
			return;
		}

		$note = sanitize_text_field(
			$settings['note'] ?: __( 'Status changed automatically by CartCue.', 'cartcue-sales-automation' )
		);

		$order->update_status( $new_status, $note );
	}
}
