<?php

namespace AutoAdmin\Bundle\Seo\Renderer;

use AutoAdmin\Bundle\Seo\Entity\SchemaOrgMetadata;
use AutoAdmin\Bundle\Seo\Model\SeoPage;
use Symfony\Component\HttpFoundation\Response;

class SchemaOrgSeoRenderer extends AbstractSeoRenderer
{
    public function render(Response $response, SeoPage $seoPage): Response
    {
        $output = '';

        // via backend
        foreach ($seoPage->getStructuredData() as $structuredData) {
            if (
                $structuredData instanceof SchemaOrgMetadata
                && !empty($jsonLd = $structuredData->getJsonLd())
            ) {
                if (stripos($jsonLd, '}{')) {
                    $jsonLd = str_replace('}{', '},{', $jsonLd);
                    $jsonLd = '['.$jsonLd.']';
                }

                $output .= "\n".$this->createTag('script', ['type' => 'application/ld+json'], $jsonLd)."\n";
            }
        }

        // via programmatic builders (aa_seo.schema_builder)
        foreach ($seoPage->getSchemaStack()->getRepresentations() as $item) {
            $output .= $item->toScript();
        }

        return $this->replaceSeoTags($response, $output, 'seo-body');
    }
}
