<?php

declare(strict_types=1);

final class MicFormNotificationBody
{
    public function build(array $form, array $submission, string $recipientEmail, array $settings): MailEnvelope
    {
        $formName = (string) ($form['name'] ?? 'Form');
        $siteTitle = myronSiteTitle();
        $subject = '[' . $siteTitle . '] New form submission: ' . $formName;
        $fields = is_array($submission['fields'] ?? null) ? $submission['fields'] : [];
        $labels = [];
        foreach (is_array($form['fields'] ?? null) ? $form['fields'] : [] as $field) {
            if (is_array($field)) {
                $labels[(string) ($field['key'] ?? '')] = strip_tags((string) ($field['label'] ?? ''));
            }
        }

        $html = '<h2>' . myronEscape($formName) . '</h2><p><small>Submitted at ' . myronEscape((string) ($submission['submitted_at'] ?? '')) . '</small></p><dl>';
        $text = $formName . "\nSubmitted at " . (string) ($submission['submitted_at'] ?? '') . "\n\n";
        foreach ($fields as $key => $value) {
            $label = $labels[(string) $key] ?? (string) $key;
            $html .= '<dt>' . myronEscape($label) . '</dt><dd>' . nl2br(myronEscape((string) $value)) . '</dd>';
            $text .= $label . ': ' . (string) $value . "\n";
        }
        $source = (string) ($submission['source_url'] ?? '');
        if ($source !== '') {
            $html .= '</dl><p>Source: <a href="' . myronEscape($source) . '">' . myronEscape($source) . '</a></p>';
            $text .= "\nSource: " . $source . "\n";
        } else {
            $html .= '</dl>';
        }
        $adminUrl = myronBuildAbsoluteAdminUrl('content.contentBanks', ['bank' => 'forms', 'edit' => (string) ($form['id'] ?? ''), 'tab' => 'submissions']);
        $html .= '<p><a href="' . myronEscape($adminUrl) . '">View this submission in MyronCMS admin</a></p>';
        $text .= "\nView in MyronCMS admin: " . $adminUrl;

        return new MailEnvelope(
            to: $recipientEmail,
            subject: $subject,
            htmlBody: $html,
            textBody: $text,
            fromEmail: (string) ($settings['from_email'] ?? ''),
            fromName: (string) ($settings['from_name'] ?? 'MyronCMS'),
        );
    }
}
