<?php
// Include your database connection just like you do on index.php
require_once 'config.php';

// Tell browsers and search engines this is an XML file
header("Content-Type: application/xml; charset=utf-8");

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">';

// 1. Array of your hardcoded static pages
$staticPages = [
    '' => '1.0', // Homepage
    'blog/' => '0.9',
    'join.php' => '0.8',
    'blog/ai-tools-directory' => '0.8',
    'About.php' => '0.6',
    'contact.php' => '0.5',
    'privacy-policy.php' => '0.4',
    'cookie-policy.php' => '0.4'
];

$baseUrl = 'https://earnwithaipro.in/';
$currentDate = date('Y-m-d');

// Output static pages
foreach ($staticPages as $url => $priority) {
    echo "<url>\n";
    echo "  <loc>{$baseUrl}{$url}</loc>\n";
    echo "  <lastmod>{$currentDate}</lastmod>\n";
    echo "  <changefreq>weekly</changefreq>\n";
    echo "  <priority>{$priority}</priority>\n";
    echo "</url>\n";
}

// 2. Automatically fetch ALL articles from your database
try {
    // We grab the slug and publish_date from your articles table
    $stmt = $pdo->query("SELECT slug, publish_date FROM articles ORDER BY id DESC");
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // If publish_date is empty, use today's date as fallback
        $lastmod = !empty($row['publish_date']) ? date("Y-m-d", strtotime($row['publish_date'])) : $currentDate;
        
        echo "<url>\n";
        echo "  <loc>{$baseUrl}blog/" . htmlspecialchars($row['slug']) . "</loc>\n";
        echo "  <lastmod>{$lastmod}</lastmod>\n";
        echo "  <changefreq>monthly</changefreq>\n";
        echo "  <priority>0.7</priority>\n";
        echo "</url>\n";
    }
} catch (PDOException $e) {
    // If db fails, silently continue so the static pages still generate
}

echo '</urlset>';
?>