<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

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

$base = rtrim((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']), '/') . '/';

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?php echo $base; ?></loc>
        <priority>1.0</priority>
        <changefreq>daily</changefreq>
    </url>
    <url>
        <loc><?php echo $base; ?>shop</loc>
        <priority>0.9</priority>
        <changefreq>daily</changefreq>
    </url>
    <url>
        <loc><?php echo $base; ?>cart</loc>
        <priority>0.5</priority>
        <changefreq>weekly</changefreq>
    </url>
    <url>
        <loc><?php echo $base; ?>checkout</loc>
        <priority>0.3</priority>
        <changefreq>weekly</changefreq>
    </url>
    <?php
    $categories = Database::fetchAll("SELECT id, slug, updated_at FROM " . DB_PREFIX . "categories WHERE status = 1");
    foreach ($categories as $cat):
    ?>
    <url>
        <loc><?php echo $base; ?>category?id=<?php echo (int)$cat['id']; ?></loc>
        <priority>0.8</priority>
        <changefreq>weekly</changefreq>
        <?php if (!empty($cat['updated_at'])): ?>
        <lastmod><?php echo date('Y-m-d', strtotime($cat['updated_at'])); ?></lastmod>
        <?php endif; ?>
    </url>
    <?php endforeach; ?>
    <?php
    $products = Database::fetchAll("SELECT id, updated_at FROM " . DB_PREFIX . "products WHERE status IN ('available', 'pre-order')");
    foreach ($products as $prod):
    ?>
    <url>
        <loc><?php echo $base; ?>product?id=<?php echo (int)$prod['id']; ?></loc>
        <priority>0.7</priority>
        <changefreq>weekly</changefreq>
        <?php if (!empty($prod['updated_at'])): ?>
        <lastmod><?php echo date('Y-m-d', strtotime($prod['updated_at'])); ?></lastmod>
        <?php endif; ?>
    </url>
    <?php endforeach; ?>
</urlset>
