<?php
declare(strict_types=1);

namespace FreshCloud\Mail\BaseUtils;

final class TextHelper
{
    private const RFC2047_PATTERN = '/=\?([^?]+)\?([BQ])\?([^?]*)\?=/i';

    public static function decodeHeader(string $header): string
    {
        return preg_replace_callback(self::RFC2047_PATTERN, function ($matches) {
            $charset = $matches[1];
            $encoding = strtoupper($matches[2]);
            $text = $matches[3];

            if ($encoding === 'B') {
                $decoded = base64_decode($text, true);
            } elseif ($encoding === 'Q') {
                $decoded = quoted_printable_decode(strtr($text, '_', ' '));
            } else {
                $decoded = $text;
            }

            return mb_convert_encoding($decoded, 'utf-8', $charset ?: 'utf-8');
        }, $header);
    }

    public static function isValidEmail(string $email): bool
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }

    public static function truncate(string $text, int $max, string $ellipsis = '...'): string
    {
        if (mb_strlen($text) <= $max) {
            return $text;
        }
        return mb_substr($text, 0, $max - mb_strlen($ellipsis)) . $ellipsis;
    }

    public static function randomToken(int $length = 32): string
    {
        return base64_encode(random_bytes($length));
    }
}