<?php
/**
 * Add Order Note Action Definition
 *
 * @package Sequensy\Integrations\WooCommerce
 * @since   1.0.0
 */

declare(strict_types=1);

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

return array(
	'type'            => 'add_order_note',
	'label'           => __( 'Add Order Note', 'sequensy' ),
	'description'     => __( 'Add a private or customer-facing note to a WooCommerce order', 'sequensy' ),
	'category'        => 'order',
	'required_fields' => array( 'order_id', 'note' ),
	'schema'          => array(
		array(
			'name'        => 'order_id',
			'type'        => 'number',
			'label'       => __( 'Order ID', 'sequensy' ),
			'description' => __( 'ID of the order to add a note to', 'sequensy' ),
			'required'    => true,
			'order'       => 1,
		),
		array(
			'name'        => 'note',
			'type'        => 'text',
			'label'       => __( 'Note', 'sequensy' ),
			'description' => __( 'The note content to add to the order', 'sequensy' ),
			'required'    => true,
			'multiline'   => true,
			'order'       => 2,
		),
		array(
			'name'        => 'is_customer_note',
			'type'        => 'boolean',
			'label'       => __( 'Customer Note', 'sequensy' ),
			'description' => __( 'Whether this note is visible to the customer', 'sequensy' ),
			'default'     => false,
			'order'       => 3,
		),
	),
	'output_fields'   => array(
		array(
			'name'        => 'order_id',
			'type'        => 'integer',
			'description' => __( 'ID of the order', 'sequensy' ),
			'example'     => '1234',
		),
		array(
			'name'        => 'note_id',
			'type'        => 'integer',
			'description' => __( 'ID of the created note', 'sequensy' ),
			'example'     => '56',
		),
		array(
			'name'        => 'is_customer_note',
			'type'        => 'boolean',
			'description' => __( 'Whether the note is visible to the customer', 'sequensy' ),
			'example'     => 'false',
		),
	),
	'handler'         => function ( array $config, array $context ): array {
		$order_id = absint( $config['order_id'] );
		$order    = wc_get_order( $order_id );

		if ( ! $order ) {
			throw new \RuntimeException(
				sprintf(
					/* translators: %d: order ID */
					esc_html__( 'Order not found: %d', 'sequensy' ),
					esc_html( $order_id )
				)
			);
		}

		$note             = sanitize_textarea_field( $config['note'] );
		$is_customer_note = ! empty( $config['is_customer_note'] ) ? 1 : 0;

		$note_id = $order->add_order_note( $note, $is_customer_note );

		if ( ! $note_id ) {
			throw new \RuntimeException( esc_html__( 'Failed to add order note', 'sequensy' ) );
		}

		return array(
			'order_id'         => $order->get_id(),
			'note_id'          => $note_id,
			'is_customer_note' => (bool) $is_customer_note,
		);
	},
);
