<?php

namespace PloverCRM\Modules\Automations\Actions;

use PloverCRM\Core\Services\PlaceholderService;

/**
 * Sends an internal email for an automation run.
 */
class SendInternalEmailAction
{
    public function execute(array $config, array $payload): array
    {
        $contact = $payload['contact'] ?? [];
        $recipients = array_values(array_unique(array_filter((array) ($config['to'] ?? []), function ($email) {
            return is_email($email);
        })));

        if (empty($recipients)) {
            throw new \RuntimeException('No valid recipient emails were provided.');
        }

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

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

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

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

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>',
        ];

        $sent = [];
        $failed = [];

        foreach ($recipients as $recipient) {
            $result = wp_mail($recipient, $subject, $body, $headers);

            if ($result) {
                $sent[] = $recipient;
            } else {
                $failed[] = $recipient;
            }
        }

        return [
            'type' => 'send_internal_email',
            'subject' => $subject,
            'recipients_sent' => $sent,
            'recipients_failed' => $failed,
        ];
    }
}
