<?php
/**
 * AddOrderNoteAction — appends a note to the WooCommerce order.
 *
 * Supports both private (admin-only) and customer-facing notes.
 * Variables like {{order.number}} are resolved before writing.
 *
 * @package CartCue\Actions
 */

namespace CartCue\Actions;

use CartCue\Context;

defined( 'ABSPATH' ) || exit;

class AddOrderNoteAction extends AbstractAction {

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

	public function get_label(): string {
		return __( 'Add internal note', 'cartcue-sales-automation' );
	}

	public function get_settings_fields(): array {
		return [
			[
				'key'     => 'note_type',
				'label'   => __( 'Note Type', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => 'private',
				'options' => [
					'private'  => __( 'Private note (admin only)', 'cartcue-sales-automation' ),
					'customer' => __( 'Customer-facing note (visible in My Account)', 'cartcue-sales-automation' ),
				],
			],
			[
				'key'         => 'note_content',
				'label'       => __( 'Note Content', 'cartcue-sales-automation' ),
				'type'        => 'textarea',
				'default'     => '',
				'placeholder' => __( 'e.g. CartCue sent win-back email to {{customer.email}}', 'cartcue-sales-automation' ),
				'rows'        => 3,
			],
		];
	}

	public function run( array $settings, Context $context ): void {
		if ( $this->is_test( $context ) ) {
			return;
		}

		$order_id = (int) ( $context->data['order_id'] ?? 0 );
		if ( ! $order_id ) {
			// No order in context — silently skip rather than throw.
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- order_id is a validated integer.
			throw new \RuntimeException( sprintf( 'AddOrderNote: order %d not found.', $order_id ) );
		}

		$note_content = sanitize_textarea_field( $settings['note_content'] ?? '' );
		if ( empty( $note_content ) ) {
			throw new \RuntimeException( 'AddOrderNote: note content is empty.' );
		}

		$note_content  = $this->process( $note_content, $context );
		$is_customer_note = ( 'customer' === ( $settings['note_type'] ?? 'private' ) ) ? 1 : 0;

		$order->add_order_note( $note_content, $is_customer_note, false );
	}
}
