<?php
/**
 * Dynamic XML Sitemap for Snipyfy.com
 * Automatically includes all published /best/ pages
 * Updates automatically when pages are published
 */

require_once __DIR__ . '/config.php';

// Set XML content type
header('Content-Type: application/xml; charset=UTF-8');

// Simple file-based cache (6 hours)
$cache_file = sys_get_temp_dir() . '/snipyfy_sitemap_cache.xml';
$cache_ttl = 6 * 60 * 60; // 6 hours

// Check cache
$use_cache = false;
if (file_exists($cache_file)) {
    $cache_age = time() - filemtime($cache_file);
    if ($cache_age < $cache_ttl) {
        $use_cache = true;
    }
}

if ($use_cache) {
    // Serve cached version
    readfile($cache_file);
    exit;
}

// Start output buffering
ob_start();

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

// Homepage
$homepage_date = date('Y-m-d');
echo "  <url>\n";
echo "    <loc>https://snipyfy.com/</loc>\n";
echo "    <lastmod>{$homepage_date}</lastmod>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>1.0</priority>\n";
echo "  </url>\n";

// Static best seller pages (existing pages)
$static_pages = [
    ['slug' => 'egg-cooker-uae', 'date' => date('Y-m-d')],
    ['slug' => 'digital-food-scale-uae', 'date' => date('Y-m-d')],
];

foreach ($static_pages as $page) {
    $url = 'https://snipyfy.com/best/' . htmlspecialchars($page['slug'], ENT_XML1);
    echo "  <url>\n";
    echo "    <loc>{$url}</loc>\n";
    echo "    <lastmod>{$page['date']}</lastmod>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>0.8</priority>\n";
    echo "  </url>\n";
}

// Dynamic published pages from database
try {
    $stmt = $pdo->prepare("
        SELECT slug, updated_at 
        FROM page_builder_pages 
        WHERE status = 'published' 
        ORDER BY updated_at DESC
    ");
    $stmt->execute();
    $published_pages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($published_pages as $page) {
        $slug = htmlspecialchars($page['slug'], ENT_XML1);
        $lastmod = date('Y-m-d', strtotime($page['updated_at']));
        $url = 'https://snipyfy.com/best/' . $slug;
        
        echo "  <url>\n";
        echo "    <loc>{$url}</loc>\n";
        echo "    <lastmod>{$lastmod}</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.8</priority>\n";
        echo "  </url>\n";
    }
} catch (Exception $e) {
    // If table doesn't exist yet, silently continue
    // This allows sitemap to work even before AI builder is used
    error_log("Sitemap: Could not fetch published pages: " . $e->getMessage());
}

// Close XML
echo '</urlset>';

// Get output and save to cache
$xml_content = ob_get_clean();

// Save to cache
file_put_contents($cache_file, $xml_content);

// Output
echo $xml_content;





