<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Core\Settings;
use App\Models\Gallery;
use App\Models\PageRepository;

/**
 * Sitemap XML + robots.txt dynamiques.
 */
final class SeoController
{
    /** @param array<string,string> $params */
    public function sitemap(Request $request, array $params): Response
    {
        // Indexation bloquée : pas de sitemap (404).
        if ((string) Settings::get('seo_noindex', '0') === '1') {
            return new Response("Not Found\n", 404, ['Content-Type' => 'text/plain; charset=UTF-8']);
        }

        $urls = [site_url('/')];
        foreach (Gallery::publishedIndexableSlugs() as $slug) {
            $urls[] = site_url('/' . $slug);
        }
        foreach (PageRepository::publishedIndexableSlugs() as $slug) {
            $urls[] = site_url('/' . $slug);
        }

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        foreach ($urls as $url) {
            $xml .= '  <url><loc>' . htmlspecialchars($url, ENT_QUOTES | ENT_XML1, 'UTF-8') . '</loc></url>' . "\n";
        }
        $xml .= '</urlset>' . "\n";

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

    /** @param array<string,string> $params */
    public function robots(Request $request, array $params): Response
    {
        // Réglage global : empêcher l'indexation de tout le site.
        if ((string) Settings::get('seo_noindex', '0') === '1') {
            $body = "User-agent: *\nDisallow: /\n";
            return new Response($body, 200, ['Content-Type' => 'text/plain; charset=UTF-8']);
        }

        $body  = "User-agent: *\n";
        $body .= "Allow: /\n";
        $body .= "Disallow: /admin\n";
        $body .= 'Sitemap: ' . site_url('/sitemap.xml') . "\n";

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