<?php
/**
 * 3Cords AI — Dynamic Sitemap.xml Generator
 * Generates XML sitemap from database for Google indexing
 * Access at: https://3cordsai.online/sitemap.xml
 */

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

// Suppress any PHP notices/warnings that might break XML
ini_set('display_errors', 0);
error_reporting(0);

// Include config
include 'config.php';
$db = getDB();

// Static pages
$static_pages = [
    ['url' => '/', 'changefreq' => 'weekly', 'priority' => '1.0'],
    ['url' => '/about.php', 'changefreq' => 'monthly', 'priority' => '0.8'],
    ['url' => '/contact.php', 'changefreq' => 'monthly', 'priority' => '0.8'],
    ['url' => '/blog.php', 'changefreq' => 'daily', 'priority' => '0.9'],
    ['url' => '/privacy.php', 'changefreq' => 'yearly', 'priority' => '0.5'],
    ['url' => '/terms.php', 'changefreq' => 'yearly', 'priority' => '0.5'],
];

// Get published blog posts from database
$blog_posts = [];
try {
    $stmt = $db->query("
        SELECT slug, updated_at, published_at 
        FROM blog_posts 
        WHERE status='published' 
        ORDER BY published_at DESC
    ");
    $blog_posts = $stmt->fetchAll();
} catch (PDOException $e) {
    // If database query fails, continue without blog posts
}

$domain = 'https://3cordsai.online';
$now = date('Y-m-d');

?><?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
    
    <!-- Static Pages -->
    <?php foreach ($static_pages as $page): ?>
    <url>
        <loc><?php echo $domain . htmlspecialchars($page['url']); ?></loc>
        <lastmod><?php echo $now; ?></lastmod>
        <changefreq><?php echo $page['changefreq']; ?></changefreq>
        <priority><?php echo $page['priority']; ?></priority>
    </url>
    <?php endforeach; ?>
    
    <!-- Blog Posts -->
    <?php foreach ($blog_posts as $post): ?>
    <url>
        <loc><?php echo $domain . '/blog/' . htmlspecialchars($post['slug']); ?></loc>
        <lastmod><?php echo date('Y-m-d', strtotime($post['updated_at'] ?: $post['published_at'])); ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
    <?php endforeach; ?>
    
</urlset>
