<?php
/**
 * XML Sitemap — dynamically generated for search engine crawling.
 * Outputs all public URLs: pages, categories, and products.
 */
// Capture any accidental whitespace from included files
ob_start();
require_once 'config/database.php';
require_once 'includes/settings.php';

// Safely get DB connection — sitemap should still work with static pages if DB is down
$db = null;
try {
    $db = (new Database())->getConnection();
} catch (Throwable $e) {
    $db = null;
}

// Use admin-configured base URL if set, otherwise auto-detect
// Protect against null $db (e.g. DB connection failure)
$settings = frefta_default_settings();
if ($db !== null) {
    try {
        $settings = frefta_load_settings($db);
    } catch (Throwable $e) {
        // Fall through with defaults
    }
}
$base = frefta_site_base_url($settings);

// ── Static pages ──────────────────────────────────────────────
$staticPages = [
    ['loc' => '/index.php',                'changefreq' => 'daily',   'priority' => '1.0'],
    ['loc' => '/categories.php',           'changefreq' => 'daily',   'priority' => '0.9'],
    ['loc' => '/shop.php',                 'changefreq' => 'daily',   'priority' => '0.9'],
    ['loc' => '/cart.php',                 'changefreq' => 'weekly',  'priority' => '0.6'],
    ['loc' => '/about.php',                'changefreq' => 'monthly', 'priority' => '0.7'],
    ['loc' => '/contact.php',              'changefreq' => 'monthly', 'priority' => '0.7'],
    ['loc' => '/privacy-policy.php',       'changefreq' => 'yearly',  'priority' => '0.4'],
    ['loc' => '/terms-conditions.php',     'changefreq' => 'yearly',  'priority' => '0.4'],
    ['loc' => '/shipping-policy.php',      'changefreq' => 'yearly',  'priority' => '0.4'],
    ['loc' => '/user-dashboard.php',       'changefreq' => 'weekly',  'priority' => '0.6'],
    ['loc' => '/order-success.php',        'changefreq' => 'monthly', 'priority' => '0.3'],
];

// ── Categories ─────────────────────────────────────────────────
$categories = [];
try {
    $stmt = $db->query("SELECT id, slug, updated_at FROM categories WHERE status = 1 ORDER BY id ASC");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // Silently continue — categories table may not exist yet
}

// ── Products ───────────────────────────────────────────────────
$products = [];
try {
    $stmt = $db->query("SELECT id, updated_at FROM products WHERE status = 1 ORDER BY id ASC");
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // Silently continue
}

// ── Render XML ─────────────────────────────────────────────────
ob_end_clean();
header('Content-Type: application/xml; charset=UTF-8');
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($staticPages as $page): ?>
    <url>
        <loc><?php echo htmlspecialchars($base . $page['loc']); ?></loc>
        <changefreq><?php echo $page['changefreq']; ?></changefreq>
        <priority><?php echo $page['priority']; ?></priority>
    </url>
<?php endforeach; ?>
<?php foreach ($categories as $cat): ?>
    <?php $slug = !empty($cat['slug']) ? urlencode($cat['slug']) : $cat['id']; ?>
    <url>
        <loc><?php echo htmlspecialchars($base . '/categories.php?category=' . $slug); ?></loc>
        <?php if (!empty($cat['updated_at'])): ?><lastmod><?php echo date('Y-m-d', strtotime($cat['updated_at'])); ?></lastmod><?php endif; ?>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
<?php endforeach; ?>
<?php foreach ($products as $product): ?>
    <url>
        <loc><?php echo htmlspecialchars($base . '/product-details.php?id=' . (int) $product['id']); ?></loc>
        <?php if (!empty($product['updated_at'])): ?><lastmod><?php echo date('Y-m-d', strtotime($product['updated_at'])); ?></lastmod><?php endif; ?>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
<?php endforeach; ?>
</urlset>
