<?php
declare(strict_types=1);

namespace App\Seo;

final class SitemapXmlRenderer
{
    /** @param list<array{loc:string,lastmod?:string}> $entries */
    public static function urlSet(array $entries): string
    {
        $xml = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
        foreach ($entries as $entry) {
            $loc = self::escape((string) ($entry['loc'] ?? ''));
            if ($loc === '') continue;
            $lastmod = trim((string) ($entry['lastmod'] ?? ''));
            $xml[] = '  <url><loc>' . $loc . '</loc>' . ($lastmod !== '' ? '<lastmod>' . self::escape($lastmod) . '</lastmod>' : '') . '</url>';
        }
        $xml[] = '</urlset>';
        return implode("\n", $xml);
    }

    /** @param list<array{loc:string,lastmod?:string}> $entries */
    public static function index(array $entries): string
    {
        $xml = ['<?xml version="1.0" encoding="UTF-8"?>', '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
        foreach ($entries as $entry) {
            $loc = self::escape((string) ($entry['loc'] ?? ''));
            if ($loc === '') continue;
            $lastmod = trim((string) ($entry['lastmod'] ?? ''));
            $xml[] = '  <sitemap><loc>' . $loc . '</loc>' . ($lastmod !== '' ? '<lastmod>' . self::escape($lastmod) . '</lastmod>' : '') . '</sitemap>';
        }
        $xml[] = '</sitemapindex>';
        return implode("\n", $xml);
    }

    private static function escape(string $value): string
    {
        return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
    }
}
