<?php

namespace PloverCRM\Modules\Automations\Services;

use PloverCRM\Core\Services\PlaceholderService;

/**
 * Renders internal email content for both previews and real sends.
 */
class InternalEmailRenderer
{
    public static function render(array $config, array $contact, array $options = []): array
    {
        $strict = !array_key_exists('strict', $options) || $options['strict'] !== false;

        $subject = trim(wp_strip_all_tags(
            PlaceholderService::parse((string) ($config['subject'] ?? ''), $contact)
        ));

        $rawBody = PlaceholderService::parse((string) ($config['body'] ?? ''), $contact, [
            'allow_rich_blocks' => true,
        ]);

        $warnings = [];

        if ($subject === '') {
            if ($strict) {
                throw new \RuntimeException('The parsed email subject is empty.');
            }

            $warnings[] = 'Email subject is empty.';
        }

        if (trim(wp_strip_all_tags($rawBody)) === '') {
            if ($strict) {
                throw new \RuntimeException('The parsed email body is empty.');
            }

            $warnings[] = 'Email body is empty.';
        }

        $bodyHasHtml = $rawBody !== wp_strip_all_tags($rawBody);
        $body = trim($rawBody) === ''
            ? ''
            : ($bodyHasHtml ? wp_kses_post($rawBody) : wpautop(esc_html($rawBody)));

        return [
            'subject' => $subject,
            'body' => $body,
            'warnings' => $warnings,
        ];
    }

    public static function buildHeaders(): array
    {
        return [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>',
        ];
    }
}
