<?php
declare(strict_types=1);

namespace App\Services;

final class MergeService
{
    public static function apply(string $text, array $contact): string
    {
        $map = [
            'first_name' => (string) ($contact['first_name'] ?? ''),
            'last_name' => (string) ($contact['last_name'] ?? ''),
            'company' => (string) ($contact['account_name'] ?? $contact['company'] ?? ''),
            'email' => (string) ($contact['email'] ?? ''),
        ];
        foreach ($map as $key => $value) {
            $safe = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
            $text = str_replace('{{' . $key . '}}', $safe, $text);
        }
        return $text;
    }

    /** @return list<string> */
    public static function tagsIn(string $text): array
    {
        $found = [];
        foreach (['first_name', 'last_name', 'company', 'email'] as $tag) {
            if (stripos($text, '{{' . $tag . '}}') !== false) {
                $found[] = $tag;
            }
        }
        return $found;
    }

    /** Replace merge tags with sample names for screens (not for sending). */
    public static function readable(string $text): string
    {
        return str_ireplace(
            ['{{first_name}}', '{{last_name}}', '{{company}}', '{{email}}'],
            ['Alex', 'Lee', 'Acme Corp', 'alex@example.com'],
            $text
        );
    }

    public static function sanitizeBody(string $html): string
    {
        $html = strip_tags($html, '<p><br><strong><b><em><i><ul><ol><li><a>');
        $html = preg_replace('/\son\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html) ?? $html;
        $html = preg_replace('/javascript\s*:/i', '', $html) ?? $html;
        return mb_substr($html, 0, 20000);
    }
}
