<?php
/**
 * Static pages sitemap
 * URL: /sitemap.xml
 */
require_once __DIR__ . '/includes/config.php';

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

$base = 'https://dorojay.com';
$today = date('Y-m-d');

$static_pages = [
    ['loc' => $base . '/',                    'changefreq' => 'daily',   'priority' => '1.0', 'lastmod' => $today],
    ['loc' => $base . '/products.php',        'changefreq' => 'daily',   'priority' => '0.9', 'lastmod' => $today],
    ['loc' => $base . '/about.php',           'changefreq' => 'monthly', 'priority' => '0.6', 'lastmod' => $today],
    ['loc' => $base . '/contact.php',         'changefreq' => 'monthly', 'priority' => '0.6', 'lastmod' => $today],
    ['loc' => $base . '/faq.php',             'changefreq' => 'monthly', 'priority' => '0.5', 'lastmod' => $today],
    ['loc' => $base . '/shipping-policy.php', 'changefreq' => 'monthly', 'priority' => '0.4', 'lastmod' => $today],
    ['loc' => $base . '/return-refund.php',   'changefreq' => 'monthly', 'priority' => '0.4', 'lastmod' => $today],
    ['loc' => $base . '/privacy-policy.php',  'changefreq' => 'monthly', 'priority' => '0.3', 'lastmod' => $today],
    ['loc' => $base . '/terms-of-service.php','changefreq' => 'monthly', 'priority' => '0.3', 'lastmod' => $today],
];

// Add category pages
try {
    $cats = db()->query("SELECT slug, updated_at FROM categories WHERE status = 'active' ORDER BY name")->fetchAll();
    foreach ($cats as $cat) {
        $static_pages[] = [
            'loc'        => $base . '/products.php?category=' . urlencode($cat['slug']),
            'changefreq' => 'weekly',
            'priority'   => '0.7',
            'lastmod'    => $cat['updated_at'] ? date('Y-m-d', strtotime($cat['updated_at'])) : $today,
        ];
    }
} catch (Exception $e) {}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<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">' . "\n";

foreach ($static_pages as $page): ?>
  <url>
    <loc><?= htmlspecialchars($page['loc']) ?></loc>
    <lastmod><?= $page['lastmod'] ?></lastmod>
    <changefreq><?= $page['changefreq'] ?></changefreq>
    <priority><?= $page['priority'] ?></priority>
  </url>
<?php endforeach;

echo '</urlset>';
