<?php


namespace AutoAdmin\Bundle\Seo\Renderer;


use AutoAdmin\Bundle\Seo\Model\Alternate;
use AutoAdmin\Bundle\Seo\Model\Meta;
use AutoAdmin\Bundle\Seo\Model\SeoPage;
use Symfony\Component\HttpFoundation\Response;

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

        if (!empty($seoPage->getTitle())) {
            $html .= $this->createTag('title', [], $seoPage->getTitle()) . "\n";
        }

        if (!empty($metas = $seoPage->getMetas())) {
            /** @var Meta $meta */
            foreach ($metas as $meta) {
                $html .= $this->createTag(
                        'meta',
                        [
                            'name' => $meta->getName(),
                            'content' => $meta->getValue(),
                        ]
                    ) . "\n";
            }
        }

        if (!empty($canonical = $seoPage->getCanonical())) {
            $html .= $this->createTag('link', ['rel' => 'canonical', 'href' => $canonical,]) . "\n";
        }

        $alternates = $seoPage->getAlternates();

        if (!empty($alternates) && count($alternates) > 1) {
            /** @var Alternate $alternate */
            foreach ($alternates as $alternate) {
                $html .= $this->createTag(
                        'link',
                        [
                            'rel' => 'alternate',
                            'hreflang' => $alternate->getHrefLang(),
                            'href' => $alternate->getHref(),
                        ]
                    ) . "\n";
            }
        }

        // finally, unstack opengraph metas
        if (!empty($metas = $seoPage->getOpenGraphMetas())) {
            /** @var Meta $meta */
            foreach ($metas as $meta) {
                $html .= $this->createTag(
                        'meta',
                        [
                            'property' => $meta->getName(),
                            'content' => $meta->getValue(),
                        ]
                    ) . "\n";
            }
        }

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