<?php

namespace PloverCRM\Core\Services;

/**
 * Applies the workspace reply-to email to outgoing messages.
 */
class ReplyToHeaderService
{
    public function init(): void
    {
        add_filter('wp_mail', [$this, 'applyReplyToHeader'], PHP_INT_MAX);
    }

    public function applyReplyToHeader(array $args): array
    {
        $replyToEmail = (string) get_option(
            GeneralSettingsPayloadBuilder::REPLY_TO_EMAIL_OPTION,
            get_option('admin_email', '')
        );

        if ($replyToEmail === '' || !is_email($replyToEmail)) {
            return $args;
        }

        $replyToHeader = 'Reply-To: ' . $replyToEmail;
        $headers = $args['headers'] ?? [];

        if (!is_array($headers)) {
            $headers = array_filter(explode("\n", str_replace("\r\n", "\n", (string) $headers)));
        }

        $headers = array_values(array_filter($headers, static function ($header) {
            return strpos(strtolower((string) $header), 'reply-to:') !== 0;
        }));
        $headers[] = $replyToHeader;

        $args['headers'] = $headers;

        return $args;
    }
}
