<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Commerce\Catalog;

use CpCreation\VitiCore\Commerce\Catalog\Api\Resource\CatalogRichText;

final class CatalogText
{
    public static function rich(?string $value): CatalogRichText
    {
        $html = null === $value ? null : mb_trim($value);
        if ('' === $html) {
            $html = null;
        }

        $plain = null;
        if (null !== $html) {
            $plain = preg_replace(
                '~<(?:br\s*/?|/p|/div|/li|/h[1-6])\s*>~iu',
                ' ',
                $html,
            ) ?? $html;
            $plain = html_entity_decode(strip_tags($plain), \ENT_QUOTES | \ENT_HTML5, 'UTF-8');
            $plain = preg_replace('/\s+/u', ' ', $plain) ?? '';
            $plain = mb_trim($plain);
            if ('' === $plain) {
                $plain = null;
            }
        }

        return new CatalogRichText($html, $plain);
    }

    public static function plain(?string $value): string
    {
        return self::rich($value)->plain ?? '';
    }
}
