<?php
/**
 * Normalizes recipe payloads for the visual email builder.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class RecipeNormalizer {

	/**
	 * @param array<string, mixed> $recipe Raw recipe array.
	 * @return array<string, mixed>
	 */
	public static function normalize( array $recipe ): array {
		if ( empty( $recipe['actions'] ) || ! is_array( $recipe['actions'] ) ) {
			return $recipe;
		}

		foreach ( $recipe['actions'] as $i => $action ) {
			if ( ! is_array( $action ) || 'send_email' !== ( $action['type'] ?? '' ) ) {
				continue;
			}

			$settings = is_array( $action['settings'] ?? null ) ? $action['settings'] : [];
			$body     = trim( (string) ( $settings['body'] ?? '' ) );

			if ( EmailBlockRenderer::is_builder_content( $body ) ) {
				$settings['body_mode'] = 'builder';
				$recipe['actions'][ $i ]['settings'] = $settings;
				continue;
			}

			if ( '' === $body ) {
				continue;
			}

			$settings['body']      = wp_json_encode( self::html_to_blocks( $body ) );
			$settings['body_mode'] = 'builder';
			$recipe['actions'][ $i ]['settings'] = $settings;
		}

		return $recipe;
	}

	/**
	 * @return array<int, array<string, mixed>>
	 */
	public static function html_to_blocks( string $html ): array {
		$blocks = [];

		if ( preg_match( '/<a[^>]+href=["\']([^"\']+)["\'][^>]*>(.*?)<\/a>/is', $html, $button_match ) ) {
			$before = trim( substr( $html, 0, (int) strpos( $html, $button_match[0] ) ) );
			$after  = trim( substr( $html, (int) strpos( $html, $button_match[0] ) + strlen( $button_match[0] ) ) );

			if ( '' !== $before ) {
				$blocks[] = [
					'type'    => 'text',
					'content' => $before,
					'align'   => 'left',
				];
			}

			$blocks[] = [
				'type'       => 'button',
				'text'       => wp_strip_all_tags( $button_match[2] ) . ' →',
				'url'        => $button_match[1],
				'bg_color'   => '#534AB7',
				'text_color' => '#ffffff',
				'align'      => 'center',
			];

			if ( '' !== $after ) {
				$blocks[] = [
					'type'    => 'text',
					'content' => $after,
					'align'   => 'left',
				];
			}

			return $blocks;
		}

		return [
			[
				'type'    => 'text',
				'content' => $html,
				'align'   => 'left',
			],
		];
	}

	/**
	 * Default send_email action for new blank plays.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	/**
	 * Build a database row payload from a recipe template.
	 *
	 * @param array<string, mixed> $recipe Recipe from Recipes::get() / Recipes::all().
	 * @param string               $status active|paused.
	 * @return array<string, mixed>
	 */
	public static function to_workflow_payload( array $recipe, string $status = 'active' ): array {
		$recipe       = self::normalize( $recipe );
		$trigger_slug = sanitize_key( (string) ( $recipe['trigger'] ?? $recipe['trigger_slug'] ?? '' ) );
		$timing       = is_array( $recipe['timing'] ?? null ) ? $recipe['timing'] : [ 'type' => 'immediate' ];
		$rules        = is_array( $recipe['rules'] ?? null ) ? $recipe['rules'] : [];
		$actions      = is_array( $recipe['actions'] ?? null ) ? $recipe['actions'] : [];
		$sequence     = is_array( $recipe['sequence'] ?? null ) ? $recipe['sequence'] : [];
		$now          = current_time( 'mysql' );

		return [
			'name'                    => sanitize_text_field( (string) ( $recipe['name'] ?? '' ) ),
			'trigger_slug'            => $trigger_slug,
			'trigger_settings'        => wp_json_encode( is_array( $recipe['trigger_settings'] ?? null ) ? $recipe['trigger_settings'] : [] ),
			'rules'                   => wp_json_encode( $rules ),
			'actions'                 => wp_json_encode( $actions ),
			'sequence'                => wp_json_encode( $sequence ),
			'timing'                  => wp_json_encode( $timing ),
			'status'                  => in_array( $status, [ 'active', 'paused' ], true ) ? $status : 'active',
			'max_runs_per_customer'   => max( 0, (int) ( $recipe['max_runs_per_customer'] ?? 0 ) ),
			'cooldown_days'           => max( 0, (int) ( $recipe['cooldown_days'] ?? 0 ) ),
			'send_to_past_matches'    => 0,
			'campaign_id'             => 0,
			'run_count'               => 0,
			'created_at'              => $now,
			'updated_at'              => $now,
		];
	}

	public static function default_email_action(): array {
		return [
			[
				'type'     => 'send_email',
				'settings' => [
					'email_preset' => '',
					'body_mode'    => 'builder',
					'subject'      => '',
					'body'         => wp_json_encode( EmailTemplates::preset_blocks( 'cart_recovery' ) ?: [] ),
				],
			],
		];
	}
}
