<?php
/**
 * sitemap.php — GanaHoyYa.online
 * Genera sitemap.xml dinámico desde la BD con caché inteligente.
 * ✅ Sin errores de XML extra content
 * ✅ Output buffering para prevenir whitespace
 * ✅ Sin tag de cierre ?> para evitar espacios finales
 */

// ── INICIO LIMPIO: Sin output antes del XML ──────────────────
// Evitar cualquier output accidental
if (ob_get_level()) ob_end_clean();
ob_start();

// Configuración de errores: NO mostrar en output XML
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/sitemap_errors.log');

// Cache inteligente
$cache_file = __DIR__ . '/cache/sitemap.xml';
$cache_ttl  = 6 * 3600; // 6 horas

// Crear directorio de caché si no existe
$cache_dir = dirname($cache_file);
if (!is_dir($cache_dir)) {
    mkdir($cache_dir, 0755, true);
}

// Servir desde caché si está vigente
if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_ttl) {
    header('Content-Type: application/xml; charset=utf-8');
    header('X-Sitemap-Cache: HIT');
    header('Cache-Control: public, max-age=' . $cache_ttl);
    readfile($cache_file);
    ob_end_flush();
    exit;
}

// Incluir conexión segura a BD (sin output)
require_once __DIR__ . '/db_secure.php';

// Validar conexión
if (!$conn || $conn->connect_error) {
    // Fallback: sitemap mínimo si hay error de BD
    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    echo '  <url><loc>https://ganahoyya.online</loc><changefreq>daily</changefreq><priority>1.0</priority></url>' . "\n";
    echo '</urlset>';
    exit;
}

date_default_timezone_set('America/Bogota');

$base    = 'https://ganahoyya.online';
$hoy     = date('Y-m-d');
$urls    = [];
$max_urls = 49000; // Límite seguro (Google: 50,000)

// ── FUNCIÓN: Generar slug SEO-friendly ─────────────────────────
function generarSlug($texto) {
    $texto = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $texto);
    $texto = strtolower($texto);
    $texto = preg_replace('/[^a-z0-9]+/i', '-', $texto);
    $texto = preg_replace('/-+/', '-', $texto);
    return trim($texto, '-');
}

// ── FUNCIÓN: Validar URL antes de agregar ─────────────────────
function esUrlValida($loc) {
    return filter_var($loc, FILTER_VALIDATE_URL) !== false 
        && strpos($loc, 'ganahoyya.online') !== false;
}

// ── FUNCIÓN: Agregar URL con validación ───────────────────────
function agregarUrl(&$urls, $loc, $priority, $freq, $lastmod, $title = null, $imagen = null) {
    global $base, $max_urls;
    
    if (count($urls) >= $max_urls) return false;
    
    $url_completa = $base . $loc;
    if (!esUrlValida($url_completa)) return false;
    
    $entry = [
        'loc'      => $loc,
        'priority' => $priority,
        'freq'     => $freq,
        'lastmod'  => $lastmod,
    ];
    
    if ($title) $entry['title'] = $title;
    if ($imagen) $entry['imagen'] = $imagen;
    
    $urls[] = $entry;
    return true;
}

// ── 1. PÁGINAS ESTÁTICAS PRINCIPALES ─────────────────────────
$estaticas = [
    ['loc'=>'/',              'priority'=>'1.0', 'freq'=>'daily',   'lastmod'=>$hoy],
    ['loc'=>'/registro',      'priority'=>'0.9', 'freq'=>'monthly', 'lastmod'=>$hoy],
    ['loc'=>'/login',         'priority'=>'0.7', 'freq'=>'monthly', 'lastmod'=>$hoy],
    ['loc'=>'/politicas',     'priority'=>'0.5', 'freq'=>'yearly',  'lastmod'=>$hoy],
    ['loc'=>'/terminos',      'priority'=>'0.5', 'freq'=>'yearly',  'lastmod'=>$hoy],
    ['loc'=>'/socios',        'priority'=>'0.8', 'freq'=>'weekly',  'lastmod'=>$hoy],
    ['loc'=>'/ganadores',     'priority'=>'0.7', 'freq'=>'weekly',  'lastmod'=>$hoy],
    ['loc'=>'/juegos',        'priority'=>'0.8', 'freq'=>'daily',   'lastmod'=>$hoy],
    ['loc'=>'/polla',         'priority'=>'0.8', 'freq'=>'daily',   'lastmod'=>$hoy],
];

foreach ($estaticas as $u) {
    agregarUrl($urls, $u['loc'], $u['priority'], $u['freq'], $u['lastmod']);
}

// ── 2. RIFAS ACTIVAS (contenido dinámico principal) ───────────
try {
    $stmt = $conn->prepare("
        SELECT id, nombre_rifa, fecha_creacion, fecha_sorteo, imagen, imagen_url, descripcion
        FROM rifas_activas
        WHERE estado = 'activo'
        ORDER BY fecha_creacion DESC
        LIMIT 500
    ");
    $stmt->execute();
    $rifas = $stmt->get_result();
    
    if ($rifas) {
        while ($r = $rifas->fetch_assoc()) {
            $fechas = array_filter([$r['fecha_sorteo'], $r['fecha_creacion']]);
            $lastmod = date('Y-m-d', strtotime(max($fechas) ?? $hoy));
            $slug = generarSlug($r['nombre_rifa']);
            
            agregarUrl($urls, '/jugar/' . $r['id'], '0.9', 'hourly', $lastmod,
                htmlspecialchars($r['nombre_rifa'], ENT_XML1),
                !empty($r['imagen_url']) ? $r['imagen_url'] : ($r['imagen'] ?? null));
            
            if ($slug && strlen($slug) >= 3) {
                agregarUrl($urls, '/rifa/' . $slug, '0.85', 'hourly', $lastmod,
                    htmlspecialchars($r['nombre_rifa'], ENT_XML1),
                    !empty($r['imagen_url']) ? $r['imagen_url'] : ($r['imagen'] ?? null));
            }
        }
    }
    $stmt->close();
} catch (Exception $e) {
    error_log('Error sitemap rifas: ' . $e->getMessage());
}

// ── 3. SORTEOS CERRADOS RECIENTES ────────────────────────────
try {
    $stmt = $conn->prepare("
        SELECT id, nombre_rifa, fecha_sorteo, imagen_url
        FROM rifas_activas
        WHERE estado IN('cerrado','finalizado','pagado')
        AND fecha_sorteo >= DATE_SUB(NOW(), INTERVAL 90 DAY)
        ORDER BY fecha_sorteo DESC
        LIMIT 50
    ");
    $stmt->execute();
    $cerrados = $stmt->get_result();
    
    if ($cerrados) {
        while ($r = $cerrados->fetch_assoc()) {
            $lastmod = date('Y-m-d', strtotime($r['fecha_sorteo']));
            agregarUrl($urls, '/jugar/' . $r['id'], '0.5', 'monthly', $lastmod,
                htmlspecialchars($r['nombre_rifa'], ENT_XML1), $r['imagen_url'] ?? null);
        }
    }
    $stmt->close();
} catch (Exception $e) {
    error_log('Error sitemap cerrados: ' . $e->getMessage());
}

// ── GENERAR XML ───────────────────────────────────────────────
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
$xml .= '        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . "\n";
$xml .= '        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"' . "\n";
$xml .= '        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9' . "\n";
$xml .= '        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n";
$xml .= '<!--' . "\n";
$xml .= '  Sitemap generado automáticamente para GanaHoyYa.online' . "\n";
$xml .= '  Fecha: ' . date('Y-m-d H:i:s T') . "\n";
$xml .= '  URLs totales: ' . count($urls) . "\n";
$xml .= '-->' . "\n\n";

foreach ($urls as $u) {
    $loc = htmlspecialchars($base . $u['loc'], ENT_XML1);
    
    $xml .= "  <url>\n";
    $xml .= "    <loc>{$loc}</loc>\n";
    
    if (!empty($u['lastmod']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $u['lastmod'])) {
        $xml .= "    <lastmod>{$u['lastmod']}</lastmod>\n";
    }
    
    $xml .= "    <changefreq>{$u['freq']}</changefreq>\n";
    $xml .= "    <priority>{$u['priority']}</priority>\n";
    
    if (!empty($u['imagen'])) {
        $img_url = strpos($u['imagen'], 'http') === 0 
            ? $u['imagen'] 
            : $base . $u['imagen'];
        
        if (filter_var($img_url, FILTER_VALIDATE_URL)) {
            $xml .= "    <image:image>\n";
            $xml .= "      <image:loc>" . htmlspecialchars($img_url, ENT_XML1) . "</image:loc>\n";
            if (!empty($u['title'])) {
                $xml .= "      <image:title>" . htmlspecialchars($u['title'], ENT_XML1) . "</image:title>\n";
            }
            $xml .= "      <image:caption>Rifa en GanaHoyYa</image:caption>\n";
            $xml .= "    </image:image>\n";
        }
    }
    
    $xml .= "  </url>\n";
}

// ── CERRAR XML CORRECTAMENTE ─────────────────────────────────
$xml .= '</urlset>';

// ── GUARDAR EN CACHÉ ─────────────────────────────────────────
$bytes = @file_put_contents($cache_file, $xml, LOCK_EX);
if ($bytes === false) {
    error_log('Error: No se pudo escribir caché de sitemap');
}

// ── SERVIR RESPUESTA LIMPIA ──────────────────────────────────
// Limpiar cualquier output previo
if (ob_get_level()) ob_end_clean();

header('Content-Type: application/xml; charset=utf-8');
header('X-Sitemap-Cache: MISS');
header('X-Sitemap-URLs: ' . count($urls));
header('Cache-Control: public, max-age=' . $cache_ttl);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');

// Output final del XML (sin espacios extras)
echo $xml;

// Cerrar conexión
if ($conn) $conn->close();

// ── SIN TAG DE CIERRE ?> PARA EVITAR ESPACIOS FINALES ────────
// Esto previene el error "Extra content at the end of the document"