<?php
// sitemap.xml - Dynamic Sitemap Generator
header('Content-Type: application/xml; charset=utf-8');

require_once 'config.php';

$domain = rtrim(BASE_URL, '/');
$today = date('Y-m-d');

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

    <!-- Homepage -->
    <url>
        <loc><?php echo $domain; ?>/</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- Static Pages -->
    <url>
        <loc><?php echo $domain; ?>/bikes.php</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>

    <url>
        <loc><?php echo $domain; ?>/parts.php</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>

    <url>
        <loc><?php echo $domain; ?>/scooters.php</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>

    <?php
    // Get all bikes for dynamic URLs
    $result = $conn->query("SELECT id, title, created_at FROM bikes ORDER BY created_at DESC");
    
    while($row = $result->fetch_assoc()):
        $slug = preg_replace('/[^a-z0-9]+/', '-', strtolower($row['title']));
        $slug = trim($slug, '-');
        $lastmod = date('Y-m-d', strtotime($row['created_at']));
    ?>
    <url>
        <loc><?php echo $domain; ?>/bike-details.php?id=<?php echo $row['id']; ?></loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endwhile; ?>

    <!-- Category Pages -->
    <url>
        <loc><?php echo $domain; ?>/bikes.php?page=1</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.7</priority>
    </url>

</urlset>