<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| ENFOQUE24 - SITEMAP DINÁMICO
|--------------------------------------------------------------------------
| Genera automáticamente el sitemap de Enfoque24.net.
| Las noticias se obtienen directamente desde la tabla "noticias".
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/conexion.php';

header('Content-Type: application/xml; charset=UTF-8');


/*
|--------------------------------------------------------------------------
| FUNCIÓN PARA ESCAPAR XML
|--------------------------------------------------------------------------
*/

function xmlEscape(string $valor): string
{
    return htmlspecialchars(
        $valor,
        ENT_XML1 | ENT_QUOTES,
        'UTF-8'
    );
}


/*
|--------------------------------------------------------------------------
| INICIO DEL XML
|--------------------------------------------------------------------------
*/

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";

echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";


/*
|--------------------------------------------------------------------------
| FUNCIÓN PARA AGREGAR URL
|--------------------------------------------------------------------------
*/

function agregarUrl(
    string $url,
    ?string $changefreq = null,
    ?string $priority = null
): void {

    echo "    <url>\n";

    echo '        <loc>' .
        xmlEscape($url) .
        "</loc>\n";

    if ($changefreq !== null) {
        echo '        <changefreq>' .
            xmlEscape($changefreq) .
            "</changefreq>\n";
    }

    if ($priority !== null) {
        echo '        <priority>' .
            xmlEscape($priority) .
            "</priority>\n";
    }

    echo "    </url>\n";
}


/*
|--------------------------------------------------------------------------
| PORTADA
|--------------------------------------------------------------------------
*/

agregarUrl(
    'https://enfoque24.net/',
    'hourly',
    '1.0'
);


/*
|--------------------------------------------------------------------------
| SECCIONES DE NOTICIAS
|--------------------------------------------------------------------------
*/

$secciones = [
    'nacional.html',
    'politica.html',
    'economia.html',
    'internacional.html',
    'deportes.html',
    'tecnologia.html',
    'salud.html',
    'entretenimiento.html',
    'opinion.html'
];

foreach ($secciones as $seccion) {

    agregarUrl(
        'https://enfoque24.net/' . $seccion,
        'hourly',
        '0.8'
    );
}


/*
|--------------------------------------------------------------------------
| PÁGINAS INSTITUCIONALES
|--------------------------------------------------------------------------
*/

$paginasInstitucionales = [
    'sobre-nosotros.html',
    'contacto.html',
    'tarifario.html',
    'politica-privacidad.html',
    'terminos-condiciones.html',
    'aviso-legal.html'
];

foreach ($paginasInstitucionales as $pagina) {

    agregarUrl(
        'https://enfoque24.net/' . $pagina,
        'monthly',
        '0.5'
    );
}


/*
|--------------------------------------------------------------------------
| NOTICIAS PUBLICADAS
|--------------------------------------------------------------------------
|
| Cada vez que cron_publisher.php agregue una noticia a MySQL,
| aparecerá automáticamente aquí gracias a su slug.
|
*/

try {

    $sql = "
        SELECT slug
        FROM noticias
        WHERE slug IS NOT NULL
          AND TRIM(slug) <> ''
        ORDER BY id DESC
    ";

    $stmt = $conexion->query($sql);

    while ($noticia = $stmt->fetch(PDO::FETCH_ASSOC)) {

        $slug = trim(
            (string) ($noticia['slug'] ?? '')
        );

        if ($slug === '') {
            continue;
        }

        /*
         * El slug ya es generado por cron_publisher.php
         * usando caracteres seguros para URL.
         */

        $url =
            'https://enfoque24.net/noticia/' .
            rawurlencode($slug);

        agregarUrl(
            $url,
            'daily',
            '0.9'
        );
    }

} catch (Throwable $e) {

    /*
     * No imprimimos el error dentro del XML porque
     * rompería el sitemap para Google.
     *
     * El error sí queda registrado en el log de PHP.
     */

    error_log(
        'Error sitemap Enfoque24: ' .
        $e->getMessage()
    );
}


/*
|--------------------------------------------------------------------------
| CERRAR XML
|--------------------------------------------------------------------------
*/

echo '</urlset>';