<?php


namespace AutoAdmin\Bundle\Seo\Controller;


use AutoAdmin\Bundle\Content\Controller\AbstractContentController;
use AutoAdmin\Bundle\Content\Entity\Domain;
use AutoAdmin\Bundle\Seo\Sitemap\SitemapRenderer;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;

class RobotsController extends AbstractContentController
{
    private SitemapRenderer $renderer;
    private RouterInterface $router;
    private ManagerRegistry $doctrine;


    public function __construct(SitemapRenderer $renderer, RouterInterface $router, ManagerRegistry $doctrine)
    {
        $this->renderer = $renderer;
        $this->router = $router;
        $this->doctrine = $doctrine;
    }


    public function index(Request $request): Response
    {
        $parts = [
            'User-agent: *',
            'Disallow: ',
        ];

        $host = $request->getHost();
        $domainRepo = $this->doctrine->getRepository(Domain::class);
        /** @var Domain[] $domains */
        $domain = $domainRepo->findOneBy(['domain' => $host,]);

        if (!$domain) {
            return new Response('No domain found', 404);
        }

        $locales = $domain->getLocales();
        foreach ($locales as $locale) {
            foreach ($this->renderer->getSections() as $section) {
                if (count($locales) == 1) {
                    $subSitemapUrl = $host . $this->router->generate('aa_seo_sitemap', ['section' => $section]);
                } else {
                    $subSitemapUrl = $host . $this->router->generate('aa_seo_sitemap', ['section' => $section, '_locale' => $locale->getCode()]);
                }
                $parts[] = sprintf('Sitemap: %s', $subSitemapUrl);
            }
        }

        $text = implode("\n", $parts) . "\n";

        return new Response($text, 200, ['content-type' => 'text/plain;charset=UTF-8']);
    }
}
