<?php

declare(strict_types=1);

namespace App\Controller\Public;

use App\Entity\Ecole;
use App\Repository\EcoleRepository;
use App\Service\PublicUrlGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class SeoController extends AbstractController
{
    #[Route('/sitemap.xml', name: 'public_sitemap', methods: ['GET'])]
    public function sitemap(EcoleRepository $ecoleRepository, PublicUrlGenerator $publicUrlGenerator): Response
    {
        $urls = [
            $publicUrlGenerator->platformUrl('/'),
            $publicUrlGenerator->platformUrl('/login'),
        ];

        foreach ($ecoleRepository->findAllActiveWithDomains() as $ecole) {
            if (!$ecole instanceof Ecole) {
                continue;
            }

            $urls[] = $publicUrlGenerator->schoolUrl($ecole);
            $urls[] = $publicUrlGenerator->registrationUrl($ecole);
        }

        $items = array_map(static fn (string $url): string => sprintf(
            "    <url>\n        <loc>%s</loc>\n    </url>",
            htmlspecialchars($url, ENT_XML1 | ENT_COMPAT, 'UTF-8')
        ), array_values(array_unique($urls)));

        $xml = sprintf(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n%s\n</urlset>\n",
            implode("\n", $items)
        );

        return new Response($xml, Response::HTTP_OK, ['Content-Type' => 'application/xml; charset=UTF-8']);
    }

    #[Route('/robots.txt', name: 'public_robots', methods: ['GET'])]
    public function robots(PublicUrlGenerator $publicUrlGenerator): Response
    {
        $content = implode("\n", [
            'User-agent: *',
            'Allow: /',
            'Disallow: /platform',
            'Disallow: /school',
            'Disallow: /admin',
            'Disallow: /dashboard',
            '',
            'Sitemap: '.$publicUrlGenerator->platformUrl('/sitemap.xml'),
            '',
        ]);

        return new Response($content, Response::HTTP_OK, ['Content-Type' => 'text/plain; charset=UTF-8']);
    }
}
