<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Marketing\Emailing;

use CpCreation\VitiCore\Marketing\Model\EmailCampaign;

final class UtmLinkEnricher
{
    public function enrichPlainText(EmailCampaign $campaign): string
    {
        $escaped = htmlspecialchars($campaign->getTextContent(), \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
        $linked = preg_replace_callback(
            '~https?://[^\s<]+~iu',
            fn (array $match): string => $this->link($match[0], $campaign),
            $escaped,
        );

        return '<div style="white-space:pre-wrap;font-family:Arial,sans-serif;line-height:1.5">'
            . ($linked ?? $escaped)
            . '</div>';
    }

    private function link(string $escapedUrl, EmailCampaign $campaign): string
    {
        $url = html_entity_decode($escapedUrl, \ENT_QUOTES | \ENT_HTML5, 'UTF-8');
        $suffix = '';
        while ('' !== $url && str_contains('.,;:!?)]}', mb_substr($url, -1))) {
            $suffix = mb_substr($url, -1) . $suffix;
            $url = mb_substr($url, 0, -1);
        }

        $parts = parse_url($url);
        if (false === $parts || !isset($parts['scheme'], $parts['host'])) {
            return $escapedUrl;
        }

        parse_str($parts['query'] ?? '', $query);
        foreach ([
            'utm_source' => $campaign->getUtmSource(),
            'utm_medium' => $campaign->getUtmMedium(),
            'utm_campaign' => $campaign->getUtmCampaign(),
            'utm_term' => $campaign->getUtmTerm(),
            'utm_content' => $campaign->getUtmContent(),
        ] as $name => $value) {
            if (null !== $value && '' !== $value) {
                $query[$name] = $value;
            }
        }

        $enriched = $parts['scheme'] . '://' . $parts['host']
            . (isset($parts['port']) ? ':' . $parts['port'] : '')
            . ($parts['path'] ?? '')
            . ([] !== $query ? '?' . http_build_query($query, '', '&', \PHP_QUERY_RFC3986) : '')
            . (isset($parts['fragment']) ? '#' . $parts['fragment'] : '');
        $safe = htmlspecialchars($enriched, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');

        return '<a href="' . $safe . '">' . $safe . '</a>'
            . htmlspecialchars($suffix, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
    }
}
