<?php

namespace Blazemedia\Affiliation\Providers\Trait;

use Blazemedia\Affiliation\AdminUserInterface\Settings\FormatsStyles;
use Blazemedia\Affiliation\Rendering\RenderResponse;

trait HasFormatsInjector {
    protected function inject(string $content, RenderResponse $renderResponse, bool $disclaimer = true, bool $bmPostMarkup = true): string {
        if ($this->renderResponse->isEmpty()) return $content;

        $content = str_replace(['&#8221;', '&#8220;', '&#8243;'], '"', $content);
        $content = str_replace(['&#8211;'], '–', $content);
        // $content = str_replace(['&rsquo;', '&lsquo;', '&#8216;', '&#8217;'], "'", $content);

        $replacements = $renderResponse->getReplacements();
        $bmPostMarkup = $renderResponse->getBMPostMarkup();
        // var_dump($replacements);die();
        if (empty($replacements) && empty($bmPostMarkup)) return $content;

        if (isset($this?->disclaimer) && !empty($replacements)) {
            $this->disclaimer->setStatus(true);

            array_map(
                fn($item) => $this->disclaimer->add($item['disclaimer'] ?? ''),
                $replacements
            );
        }

        // var_dump(array_map(fn($item) => [
        //     'html' => htmlentities($item['html']),
        //     'markup' => $item['markup']
        // ],
        //     $replacements));
        // var_dump($content);
        // die();


        foreach ($replacements as $replacement) {
            $content = str_replace(
                $replacement['html'], 
                $replacement['markup'], 
                $content
            );
        }

        return $content . $bmPostMarkup;
    }


    protected function injectStyles(RenderResponse $renderResponse): void {
        $formatsStyles = json_decode(FormatsStyles::getCss(), true);

        $styles = '';
        foreach ($formatsStyles as $format => $style) {
            if (!empty($style)) {
                $styles .= $style;
            }
        }

        echo "<style title=\"affiliation\">{$styles}</style>";
    }
}
