<?php
declare(strict_types=1);

/** Sitemap XML seguro: todos los valores dinámicos se limpian y escapan antes de insertarlos. */
require __DIR__ . '/app/bootstrap.php';

header('Content-Type: application/xml; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

/**
 * Escapa texto para XML 1.0. htmlspecialchars sustituye UTF-8 inválido;
 * después quitamos los caracteres de control que XML 1.0 no permite.
 */
$xmlEscape = static function (mixed $value): string {
    $escaped = htmlspecialchars((string)$value, ENT_XML1 | ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    $clean = preg_replace('/[\\x{0}-\\x{8}\\x{B}\\x{C}\\x{E}-\\x{1F}\\x{FFFE}\\x{FFFF}]/u', '', $escaped);
    return $clean ?? '';
};

$today = date('Y-m-d');
$xmlDate = static function (mixed $value) use ($today): string {
    $date = substr(trim((string)$value), 0, 10);
    if (!preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $date)) return $today;
    [$year, $month, $day] = array_map('intval', explode('-', $date));
    return checkdate($month, $day, $year) ? $date : $today;
};

$catalogRaw = @file_get_contents(Catalog::FILE);
$catalog = is_string($catalogRaw) ? json_decode($catalogRaw, true) : null;
if (!is_array($catalog)) $catalog = ['products' => [], 'categories' => []];
$categories = is_array($catalog['categories'] ?? null) ? $catalog['categories'] : [];
$products = is_array($catalog['products'] ?? null) ? $catalog['products'] : [];
$generated = $xmlDate($catalog['generated'] ?? $today);
$siteBase = rtrim((string)Config::get('site.url', ''), '/');

$entry = static function (string $path, mixed $lastmod = '', array $images = [], string $priority = '0.6') use ($xmlEscape, $xmlDate, $today, $siteBase): string {
    // Las rutas de la tienda se construyen siempre bajo el dominio configurado.
    $loc = $siteBase . '/' . ltrim($path, '/');
    $lastmodText = $xmlDate($lastmod ?: $today);
    $priority = in_array($priority, ['1.0', '0.8', '0.7', '0.6', '0.5', '0.4', '0.3'], true) ? $priority : '0.5';
    $separator = str_contains($loc, '?') ? '&' : '?';
    $output = '';

    foreach (['es' => $loc, 'en' => $loc . $separator . 'lang=en'] as $language => $url) {
        $output .= "  <url>\n";
        $output .= '    <loc>' . $xmlEscape($url) . "</loc>\n";
        $output .= '    <lastmod>' . $xmlEscape($lastmodText) . "</lastmod>\n";
        $output .= '    <priority>' . $priority . "</priority>\n";
        $output .= '    <xhtml:link rel="alternate" hreflang="es-MX" href="' . $xmlEscape($loc) . "\" />\n";
        $output .= '    <xhtml:link rel="alternate" hreflang="en" href="' . $xmlEscape($loc . $separator . 'lang=en') . "\" />\n";
        $output .= '    <xhtml:link rel="alternate" hreflang="x-default" href="' . $xmlEscape($loc) . "\" />\n";

        foreach (array_slice($images, 0, 5) as $image) {
            if (!is_string($image) || trim($image) === '') continue;
            $imageUrl = $siteBase . '/' . ltrim($image . '-1200.webp', '/');
            $output .= '    <image:image><image:loc>' . $xmlEscape($imageUrl) . "</image:loc></image:image>\n";
        }
        $output .= "  </url>\n";
    }
    return $output;
};

$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xml .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\">\n";
$xml .= $entry('', $generated, [], '1.0');
$xml .= $entry('categoria/todo', $generated, [], '0.8');

foreach ($categories as $category) {
    $slug = is_array($category) ? (string)($category['slug'] ?? '') : '';
    if ($slug !== '') $xml .= $entry('categoria/' . $slug, $generated, [], '0.8');
}

foreach ($products as $product) {
    if (!is_array($product)) continue;
    $slug = (string)($product['slug'] ?? '');
    if ($slug === '') continue;
    $images = is_array($product['img'] ?? null) ? $product['img'] : [];
    $xml .= $entry('producto/' . $slug, $generated, $images, '0.7');
}

try {
    $posts = Blog::latest(200);
    if (is_array($posts) && $posts) {
        $xml .= $entry('blog', $generated, [], '0.5');
        foreach ($posts as $post) {
            if (!is_array($post)) continue;
            $slug = (string)($post['slug'] ?? '');
            if ($slug === '') continue;
            $xml .= $entry('blog/' . $slug, $post['date'] ?? $generated, [], '0.5');
        }
    }
} catch (Throwable $error) {
    // El mapa principal sigue disponible aunque el módulo de blog falle.
    if (class_exists('Log')) Log::error('No se pudieron agregar entradas del blog al sitemap', ['msg' => $error->getMessage()]);
}

foreach (array_keys(Legal::PAGES) as $slug) $xml .= $entry((string)$slug, $generated, [], '0.3');
$xml .= "</urlset>\n";

// Si el servidor tiene DOM, valida el XML generado antes de publicarlo.
if (class_exists('DOMDocument')) {
    $previous = libxml_use_internal_errors(true);
    $document = new DOMDocument();
    $valid = $document->loadXML($xml, LIBXML_NONET);
    $parseErrors = libxml_get_errors();
    libxml_clear_errors();
    libxml_use_internal_errors($previous);
    if (!$valid) {
        if (class_exists('Log')) Log::error('El sitemap generado no es XML válido', ['line' => $parseErrors[0]->line ?? null, 'column' => $parseErrors[0]->column ?? null, 'message' => trim($parseErrors[0]->message ?? '')]);
        http_response_code(500);
        header('Content-Type: text/plain; charset=UTF-8');
        echo 'No se pudo generar un sitemap XML válido. Revisa el registro de errores de PHP.';
        exit;
    }
}

echo $xml;
