<?php
/**
 * Sitemap XML Dinámico
 * Archivo: sitemap.xml
 */

header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: max-age=86400');  // Cache de 24 horas

require_once __DIR__ . '/config/database.php';

// Iniciar XML
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// Páginas principales
$paginas_principales = array(
    array('url' => '/meme/', 'changefreq' => 'weekly', 'priority' => '1.0'),
    array('url' => '/meme/auth/login.php', 'changefreq' => 'monthly', 'priority' => '0.7'),
    array('url' => '/meme/auth/registro.php', 'changefreq' => 'monthly', 'priority' => '0.7'),
);

foreach ($paginas_principales as $pagina) {
    $xml .= '  <url>' . "\n";
    $xml .= '    <loc>http://plantillamemes.com' . $pagina['url'] . '</loc>' . "\n";
    $xml .= '    <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n";
    $xml .= '    <changefreq>' . $pagina['changefreq'] . '</changefreq>' . "\n";
    $xml .= '    <priority>' . $pagina['priority'] . '</priority>' . "\n";
    $xml .= '  </url>' . "\n";
}

// Obtener todos los memes publicados
try {
    $stmt = $pdo->query("
        SELECT id, fecha_creacion 
        FROM memes 
        WHERE publicado = TRUE 
        ORDER BY fecha_creacion DESC 
        LIMIT 50000
    ");
    
    while ($meme = $stmt->fetch()) {
        $fecha = date('Y-m-d', strtotime($meme['fecha_creacion']));
        $xml .= '  <url>' . "\n";
        $xml .= '    <loc>http://plantillamemes.com/meme/detalle.php?id=' . htmlspecialchars($meme['id']) . '</loc>' . "\n";
        $xml .= '    <lastmod>' . $fecha . '</lastmod>' . "\n";
        $xml .= '    <changefreq>weekly</changefreq>' . "\n";
        $xml .= '    <priority>0.8</priority>' . "\n";
        $xml .= '  </url>' . "\n";
    }
} catch (Exception $e) {
    error_log("Error en sitemap: " . $e->getMessage());
}

$xml .= '</urlset>';

echo $xml;
?>
