<?php

namespace App\Support;

class CatalogThemeApplicator
{
    public static function apply(string $html, string $bodyClass): string
    {
        $bodyClass = trim($bodyClass);

        if ($bodyClass === '') {
            return $html;
        }

        $escaped = htmlspecialchars($bodyClass, ENT_QUOTES, 'UTF-8');

        if (preg_match('/<body\b([^>]*)\bclass="[^"]*"/i', $html) === 1) {
            $replaced = preg_replace(
                '/<body\b([^>]*)\bclass="[^"]*"/i',
                '<body$1class="'.$escaped.'"',
                $html,
                1,
            );

            return is_string($replaced) ? $replaced : $html;
        }

        if (preg_match('/<body\b([^>]*)>/i', $html) === 1) {
            $replaced = preg_replace(
                '/<body\b([^>]*)>/i',
                '<body$1 class="'.$escaped.'">',
                $html,
                1,
            );

            return is_string($replaced) ? $replaced : $html;
        }

        return $html;
    }
}
