<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/app/config/database.php';

header('Content-Type: application/xml; charset=utf-8');

$pdo = getDbConnection();
$baseUrl = rtrim($_ENV['APP_URL'] ?? 'http://localhost/kitsnculture/public', '/');

// Fetch Active Products
$products = $pdo->query("SELECT slug, updated_at FROM products WHERE is_active = 1 ORDER BY id DESC")->fetchAll();

// Fetch Active Collections
$collections = $pdo->query("SELECT slug FROM collections WHERE is_active = 1 ORDER BY id ASC")->fetchAll();

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <!-- Static Canonical Roots -->
    <url>
        <loc><?= htmlspecialchars($baseUrl . '/index.php', ENT_XML1, 'UTF-8') ?></loc>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($baseUrl . '/shop.php', ENT_XML1, 'UTF-8') ?></loc>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($baseUrl . '/shipping-returns.php', ENT_XML1, 'UTF-8') ?></loc>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($baseUrl . '/terms.php', ENT_XML1, 'UTF-8') ?></loc>
        <changefreq>monthly</changefreq>
        <priority>0.4</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($baseUrl . '/privacy.php', ENT_XML1, 'UTF-8') ?></loc>
        <changefreq>monthly</changefreq>
        <priority>0.4</priority>
    </url>

    <!-- Dynamic Products -->
    <?php foreach ($products as $p): ?>
    <url>
        <loc><?= htmlspecialchars($baseUrl . '/product.php?slug=' . urlencode($p['slug']), ENT_XML1, 'UTF-8') ?></loc>
        <lastmod><?= date('Y-m-d', strtotime($p['updated_at'] ?? 'now')) ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endforeach; ?>
</urlset>