<?php
header('Content-Type: application/xml');
require_once 'includes/config.php';
require_once 'includes/functions.php';

$pdo = getDBConnection();
$baseUrl = SITE_URL;

$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

// Static pages
$pages = ['', 'shop.php', 'about.php', 'contact.php', 'privacy-policy.php', 'terms.php', 'refund-policy.php'];
foreach ($pages as $page) {
    $xml .= '<url>';
    $xml .= '<loc>' . $baseUrl . $page . '</loc>';
    $xml .= '<changefreq>weekly</changefreq>';
    $xml .= '<priority>0.8</priority>';
    $xml .= '</url>';
}

// Products
$products = $pdo->query("SELECT id, slug, updated_at FROM products WHERE status = 'active'");
foreach ($products as $product) {
    $xml .= '<url>';
    $xml .= '<loc>' . $baseUrl . 'product/' . $product['id'] . '/' . $product['slug'] . '</loc>';
    $xml .= '<lastmod>' . date('Y-m-d', strtotime($product['updated_at'])) . '</lastmod>';
    $xml .= '<changefreq>weekly</changefreq>';
    $xml .= '<priority>0.6</priority>';
    $xml .= '</url>';
}

// Categories
$categories = $pdo->query("SELECT id, slug FROM categories WHERE status = 'active'");
foreach ($categories as $category) {
    $xml .= '<url>';
    $xml .= '<loc>' . $baseUrl . 'category/' . $category['id'] . '/' . $category['slug'] . '</loc>';
    $xml .= '<changefreq>weekly</changefreq>';
    $xml .= '<priority>0.5</priority>';
    $xml .= '</url>';
}

$xml .= '</urlset>';
echo $xml;