<?php
/**
 * YayMailBridge — optional Phase 1 bridge for rendering CartCue emails via YayMail.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class YayMailBridge {

	public static function init(): void {
		add_filter( 'cartcue_pre_send_email', [ __CLASS__, 'maybe_render_with_yaymail' ], 8, 3 );
		add_filter( 'yaymail_extra_shortcodes', [ __CLASS__, 'register_extra_shortcodes' ], 10, 2 );
	}

	/**
	 * Render CartCue email with a selected YayMail template when available.
	 *
	 * @param string $html
	 * @param int    $workflow_id
	 * @param array  $context
	 * @return string
	 */
	public static function maybe_render_with_yaymail( string $html, int $workflow_id, array $context ): string {
		if ( '' === trim( $html ) || ! empty( $context['is_plain'] ) ) {
			return $html;
		}

		if ( ! class_exists( '\YayMail\YayMailTemplate' ) ) {
			return $html;
		}

		$template_name = self::resolve_template_name( $workflow_id, $context );
		if ( '' === $template_name ) {
			return $html;
		}
		if ( ! self::template_exists( $template_name ) ) {
			return $html;
		}

		try {
			$template = new \YayMail\YayMailTemplate( $template_name );
			if ( ! $template->is_exists() || ! $template->is_enabled() ) {
				return $html;
			}

			$render_data = [
				'is_sample'             => ! empty( $context['_is_test'] ),
				'cartcue_email_body'    => isset( $context['raw_body'] ) ? (string) $context['raw_body'] : $html,
				'cartcue_wrapped_email' => $html,
				'cartcue_subject'       => isset( $context['subject'] ) ? (string) $context['subject'] : '',
				'cartcue_customer_email'=> isset( $context['customer_email'] ) ? (string) $context['customer_email'] : '',
				'cartcue_workflow_id'   => $workflow_id,
				'cartcue_context'       => $context,
			];

			$render_data = apply_filters( 'cartcue_yaymail_render_data', $render_data, $workflow_id, $context, $html );
			$content     = $template->get_content( $render_data );

			if ( is_string( $content ) && '' !== trim( $content ) ) {
				return $content;
			}
		} catch ( \Throwable $e ) {
			// Fail open: preserve original CartCue email output if YayMail rendering fails.
		}

		return $html;
	}

	/**
	 * Register shortcodes that can be used inside YayMail templates.
	 *
	 * @param array $shortcodes
	 * @param array $data
	 * @return array
	 */
	public static function register_extra_shortcodes( array $shortcodes, array $data ): array {
		if ( ! isset( $data['cartcue_context'] ) ) {
			return $shortcodes;
		}

		$shortcodes[] = [
			'name'     => 'cartcue_email_body',
			'callback' => [ __CLASS__, 'shortcode_email_body' ],
		];

		$shortcodes[] = [
			'name'     => 'cartcue_subject',
			'callback' => [ __CLASS__, 'shortcode_subject' ],
		];

		$shortcodes[] = [
			'name'     => 'cartcue_customer_email',
			'callback' => [ __CLASS__, 'shortcode_customer_email' ],
		];

		return $shortcodes;
	}

	public static function shortcode_email_body( array $data ): string {
		return wp_kses_post( (string) ( $data['cartcue_email_body'] ?? '' ) );
	}

	public static function shortcode_subject( array $data ): string {
		return esc_html( (string) ( $data['cartcue_subject'] ?? '' ) );
	}

	public static function shortcode_customer_email( array $data ): string {
		return esc_html( (string) ( $data['cartcue_customer_email'] ?? '' ) );
	}

	private static function resolve_template_name( int $workflow_id, array $context ): string {
		$settings      = get_option( 'cartcue_settings', [] );
		$default_name  = is_array( $settings ) ? (string) ( $settings['yaymail_template'] ?? '' ) : '';
		$template_name = apply_filters( 'cartcue_yaymail_template_name', $default_name, $workflow_id, $context );
		return is_string( $template_name ) ? sanitize_key( $template_name ) : '';
	}

	private static function template_exists( string $template_name ): bool {
		$template_post = get_posts(
			[
				'post_type'      => 'yaymail_template',
				'post_status'    => 'publish',
				'posts_per_page' => 1,
				'fields'         => 'ids',
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- constrained lookup (single published post id) by plugin-defined template meta.
				'meta_query'     => [
					[
						'key'   => '_yaymail_template',
						'value' => $template_name,
					],
				],
			]
		);

		return ! empty( $template_post );
	}
}
