<?php
declare(strict_types=1);

/**
 * Genera sitemap-2026.xml con los nombres de la tabla homeopatia.
 * Navegador: /crearsitemap2026.xml (ruta definida en .htaccess).
 * Consola o cron: php crearsitemap2026.php
 */

ini_set('display_errors', '0');

header('X-Robots-Tag: index, follow', true);
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Content-Type: application/xml; charset=UTF-8');

/** Usa la misma conversion de nombres que el indice por-letra.php. */
function sitemap2026Slug(string $nombre): string
{
    $nombre = mb_strtolower($nombre, 'UTF-8');
    $nombre = str_replace(
        ['á', 'é', 'í', 'ó', 'ú', 'ñ', 'ä', 'ë', 'ï', 'ö', 'ü'],
        ['a', 'e', 'i', 'o', 'u', 'n', 'a', 'e', 'i', 'o', 'u'],
        $nombre
    );
    $nombre = (string) preg_replace('/[^a-z0-9\s-]/', '', $nombre);
    $nombre = (string) preg_replace('/[\s-]+/', '-', $nombre);

    return trim($nombre, '-');
}

$homeopatia = null;
$resultado = null;
$temporal = null;
$fallo = false;

try {
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    if (!defined('APP_RUNNING')) {
        define('APP_RUNNING', true);
    }

    // Evita que los saltos de linea de la configuracion alteren el XML.
    ob_start();
    try {
        require_once __DIR__ . '/Connections/homeopatia.php';
    } finally {
        ob_end_clean();
    }

    mysqli_select_db($homeopatia, $database_homeopatia);
    $resultado = mysqli_query($homeopatia, 'SELECT nombre FROM homeopatia ORDER BY nombre ASC');

    $urls = [];
    while ($fila = mysqli_fetch_assoc($resultado)) {
        $slug = sitemap2026Slug((string) ($fila['nombre'] ?? ''));
        if ($slug === '') {
            continue;
        }

        // Una sola entrada por URL, aunque haya nombres repetidos.
        $urls[$slug] = 'https://homeopatiageneral.com/' . $slug . '.html';
    }

    if ($urls === []) {
        throw new RuntimeException('La consulta no produjo ninguna URL valida.');
    }
    if (count($urls) > 50000) {
        throw new RuntimeException('Se requieren varios sitemaps: hay mas de 50000 URL.');
    }

    $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>\n    <loc>";
        $xml .= htmlspecialchars($url, ENT_XML1 | ENT_QUOTES, 'UTF-8');
        $xml .= "</loc>\n  </url>\n";
    }
    $xml .= "</urlset>\n";

    if (strlen($xml) > 50 * 1024 * 1024) {
        throw new RuntimeException('El sitemap supera el limite de 50 MB.');
    }

    // Reemplaza el sitemap solo despues de tener el archivo completo.
    $destino = __DIR__ . '/sitemap-2026.xml';
    $temporal = tempnam(__DIR__, '.sitemap-2026-');
    if ($temporal === false) {
        throw new RuntimeException('No se pudo crear el archivo temporal.');
    }
    if (@file_put_contents($temporal, $xml, LOCK_EX) !== strlen($xml)) {
        throw new RuntimeException('No se pudo escribir el sitemap completo.');
    }
    if (!@chmod($temporal, 0644) || !@rename($temporal, $destino)) {
        throw new RuntimeException('No se pudo guardar sitemap-2026.xml.');
    }
    $temporal = null;

    if (PHP_SAPI === 'cli') {
        echo 'sitemap-2026.xml generado: ' . count($urls) . " URL.\n";
    } else {
        echo $xml;
    }
} catch (Throwable $error) {
    $fallo = true;
    error_log('crearsitemap2026: ' . $error->getMessage());
    $mensaje = 'No se pudo generar sitemap-2026.xml. Revise la conexion a la base de datos y los permisos de escritura.';

    if (PHP_SAPI === 'cli') {
        fwrite(STDERR, $mensaje . "\n");
    } else {
        http_response_code(500);
        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<error>' . htmlspecialchars($mensaje, ENT_XML1 | ENT_QUOTES, 'UTF-8') . "</error>\n";
    }
} finally {
    if (is_string($temporal) && is_file($temporal)) {
        @unlink($temporal);
    }
    if ($resultado instanceof mysqli_result) {
        mysqli_free_result($resultado);
    }
    if ($homeopatia instanceof mysqli) {
        mysqli_close($homeopatia);
    }
}

if ($fallo) {
    exit(1);
}
