<?php
/**
 * SendEmailAction — sends an HTML email to the customer (or a custom address).
 *
 * @package CartCue\Actions
 */

namespace CartCue\Actions;

use CartCue\Context;
use CartCue\EmailTemplates;
use CartCue\MarketingConsent;
use CartCue\Unsubscribe;

defined( 'ABSPATH' ) || exit;

class SendEmailAction extends AbstractAction {

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

	public function get_label(): string {
		return __( 'Send a personalized email', 'cartcue-sales-automation' );
	}

	public function get_settings_fields(): array {
		$preset_options = [];
		foreach ( EmailTemplates::presets() as $key => $preset ) {
			$preset_options[ $key ] = $preset['label'];
		}

		return [
			[
				'key'     => 'email_preset',
				'label'   => __( 'Email template', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => '',
				'options' => $preset_options,
			],
			[
				'key'     => 'body_mode',
				'label'   => '',
				'type'    => 'hidden',
				'default' => 'builder',
			],
			[
				'key'         => 'to',
				'label'       => __( 'To (email address)', 'cartcue-sales-automation' ),
				'type'        => 'text',
				'async_source' => 'customers',
				'placeholder' => __( 'Leave empty to send to customer', 'cartcue-sales-automation' ),
				'default'     => '',
			],
			[
				'key'         => 'from_name',
				'label'       => __( 'From Name', 'cartcue-sales-automation' ),
				'type'        => 'text',
				'placeholder' => get_bloginfo( 'name' ),
				'default'     => '',
			],
			[
				'key'         => 'from_email',
				'label'       => __( 'From Email', 'cartcue-sales-automation' ),
				'type'        => 'text',
				'placeholder' => get_option( 'admin_email' ),
				'default'     => '',
			],
			[
				'key'         => 'subject',
				'label'       => __( 'Subject', 'cartcue-sales-automation' ),
				'type'        => 'text',
				'default'     => '',
				'placeholder' => __( 'e.g. Thanks for your order, {{customer.first_name}}!', 'cartcue-sales-automation' ),
			],
			[
				'key'         => 'body',
				'label'       => __( 'Email Body', 'cartcue-sales-automation' ),
				'type'        => 'textarea',
				'default'     => '',
				'placeholder' => __( 'Write your email here. Use {{customer.first_name}}, {{order.number}}, {{order.total}}, {{shop.name}} etc.', 'cartcue-sales-automation' ),
				'rows'        => 10,
			],
			[
				'key'     => 'content_format',
				'label'   => __( 'Format', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => 'html',
				'options' => [
					'html'  => __( 'HTML (styled)', 'cartcue-sales-automation' ),
					'plain' => __( 'Plain text', 'cartcue-sales-automation' ),
				],
			],
			[
				'key'         => 'bcc',
				'label'       => __( 'BCC (optional)', 'cartcue-sales-automation' ),
				'type'        => 'text',
				'placeholder' => __( 'Comma-separated addresses', 'cartcue-sales-automation' ),
				'default'     => '',
			],
		];
	}

	/**
	 * @throws \RuntimeException
	 */
	public function run( array $settings, Context $context ): void {
		$data    = $context->all();
		$subject = sanitize_text_field( $settings['subject'] ?? '' );
		$is_plain = 'plain' === ( $settings['content_format'] ?? 'html' );
		$body_raw = $settings['body'] ?? '';

		if ( ! $is_plain && \CartCue\EmailBlockRenderer::is_builder_content( $body_raw ) ) {
			$body = \CartCue\EmailBlockRenderer::to_html( $body_raw );
		} else {
			$body = $is_plain
				? sanitize_textarea_field( wp_unslash( $body_raw ) )
				: wp_kses_post( $body_raw );
		}

		if ( empty( $subject ) || empty( $body ) ) {
			throw new \RuntimeException( 'Send Email action is missing subject or body.' );
		}

		// Resolve recipient.
		$to_raw = trim( $settings['to'] ?? '' );
		$to     = $to_raw ? sanitize_email( $this->process( $to_raw, $context ) ) : sanitize_email( $context->data['customer_email'] ?? '' );

		if ( ! is_email( $to ) ) {
			throw new \RuntimeException( sprintf( 'Send Email action: invalid recipient address "%s".', esc_html( $to ) ) );
		}

		if ( Unsubscribe::is_suppressed( $to ) ) {
			return;
		}

		if ( ! MarketingConsent::can_send_to( $to ) ) {
			return;
		}

		// Process template variables.
		$subject = $this->process( $subject, $context );
		$body    = $this->process( $body, $context );

		// Add [TEST] prefix to subject for test runs.
		if ( ! empty( $data['_is_test'] ) ) {
			$subject = '[TEST] ' . $subject;
		}

		// Sender override.
		$args = [
			'workflow_id' => $data['workflow_id'] ?? 0,
			'plain'       => $is_plain,
			'is_test'     => ! empty( $data['_is_test'] ),
		];
		if ( ! empty( $settings['from_name'] ) ) {
			$args['from_name'] = sanitize_text_field( $this->process( $settings['from_name'], $context ) );
		}
		if ( ! empty( $settings['from_email'] ) && is_email( $settings['from_email'] ) ) {
			$args['from_email'] = sanitize_email( $settings['from_email'] );
		}
		$bcc_raw = trim( (string) ( $settings['bcc'] ?? '' ) );
		if ( '' !== $bcc_raw ) {
			$args['bcc'] = $this->process( $bcc_raw, $context );
		}

		$sent = $this->plugin->mailer->send( $to, $subject, $body, $args );

		if ( ! $sent ) {
			throw new \RuntimeException( sprintf( 'wp_mail() failed for recipient "%s".', esc_html( $to ) ) );
		}
	}
}
