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

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

$xml = new SimpleXMLElement('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>');

function add_url($xml, $loc, $priority = '0.8', $changefreq = 'weekly') {
    $url = $xml->addChild('url');
    $url->addChild('loc', htmlspecialchars($loc));
    $url->addChild('lastmod', date('Y-m-d'));
    $url->addChild('changefreq', $changefreq);
    $url->addChild('priority', $priority);
}

// Core Pages
add_url($xml, SITE_URL . '/', '1.0', 'daily');
add_url($xml, SITE_URL . '/shop.php', '0.9', 'daily');
add_url($xml, SITE_URL . '/new_arrivals.php', '0.9', 'daily');
add_url($xml, SITE_URL . '/privacy_policy.php', '0.3', 'monthly');
add_url($xml, SITE_URL . '/terms_conditions.php', '0.3', 'monthly');
add_url($xml, SITE_URL . '/refund_policy.php', '0.3', 'monthly');
add_url($xml, SITE_URL . '/shipping_policy.php', '0.3', 'monthly');

// Category Pages
$categories = $conn->query("SELECT slug FROM categories ORDER BY name ASC");
while ($c = $categories->fetch_assoc()) {
    add_url($xml, SITE_URL . '/shop.php?category=' . $c['slug'], '0.8', 'weekly');
}

// Product Pages
$products = $conn->query("SELECT slug FROM products WHERE is_active = 1 ORDER BY id DESC");
while ($p = $products->fetch_assoc()) {
    add_url($xml, SITE_URL . '/product.php?slug=' . $p['slug'], '0.8', 'daily');
}

// CMS Managed Pages
$res_pages = $conn->query("SHOW TABLES LIKE 'pages'");
if ($res_pages && $res_pages->num_rows > 0) {
    $pages = $conn->query("SELECT slug FROM pages WHERE is_active = 1 ORDER BY title ASC");
    if ($pages) {
        while ($pg = $pages->fetch_assoc()) {
            add_url($xml, SITE_URL . '/page.php?slug=' . $pg['slug'], '0.7', 'weekly');
        }
    }
}

echo $xml->asXML();
