<?php
/**
 * عمارت ۵ دری - نقشه سایت پویا (خروجی XML)
 * این فایل .xml است اما برای بازتاب خودکار محصولات/دسته‌بندی‌های جدید،
 * به‌عنوان PHP روی سرور اجرا می‌شود (نیازمند دایرکتیو AddType در .htaccess)
 */

define('EMARAT_APP', true);
require_once __DIR__ . '/includes/config.php';

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

$urls = [];

$staticPages = ['index.php', 'products.php', 'about.php', 'contact.php'];
foreach ($staticPages as $page) {
    $urls[] = ['loc' => BASE_URL . '/' . $page, 'priority' => '0.8', 'changefreq' => 'daily'];
}

$categories = db()->fetchAll("SELECT slug, updated_at FROM categories WHERE is_active = 1");
foreach ($categories as $cat) {
    $urls[] = [
        'loc'        => BASE_URL . '/category.php?slug=' . $cat['slug'],
        'lastmod'    => date('c', strtotime($cat['updated_at'] ?? 'now')),
        'priority'   => '0.7',
        'changefreq' => 'daily',
    ];
}

$products = db()->fetchAll("SELECT slug, updated_at FROM products WHERE is_active = 1");
foreach ($products as $product) {
    $urls[] = [
        'loc'        => BASE_URL . '/product.php?slug=' . $product['slug'],
        'lastmod'    => date('c', strtotime($product['updated_at'] ?? 'now')),
        'priority'   => '0.9',
        'changefreq' => 'weekly',
    ];
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($urls as $url): ?>
    <url>
        <loc><?= htmlspecialchars($url['loc'], ENT_XML1) ?></loc>
        <?php if (!empty($url['lastmod'])): ?><lastmod><?= $url['lastmod'] ?></lastmod><?php endif; ?>
        <changefreq><?= $url['changefreq'] ?></changefreq>
        <priority><?= $url['priority'] ?></priority>
    </url>
<?php endforeach; ?>
</urlset>
