<?php

require_once __DIR__ . '/common.php';

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

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
$base   = $scheme . '://' . $host;

$urls = [];


$urls[] = [
    'loc' => $base . '/index.php',
    'priority' => '1.0',
];

try {
    $pdo = db();

    
    $stmt = $pdo->query("
        SELECT id, published_at
        FROM articles
        WHERE status = 'published'
        ORDER BY published_at DESC, id DESC
        LIMIT 500
    ");
    while ($row = $stmt->fetch()) {
        $loc = $base . '/post.php?id=' . (int)$row['id'];
        $urls[] = [
            'loc' => $loc,
            'lastmod' => !empty($row['published_at']) ? date('c', (int)$row['published_at']) : null,
            'priority' => '0.8',
        ];
    }

    
    $stmt = $pdo->query("SELECT id FROM categories ORDER BY id ASC");
    while ($row = $stmt->fetch()) {
        $urls[] = [
            'loc' => $base . '/category.php?id=' . (int)$row['id'],
            'priority' => '0.6',
        ];
    }

    
    $stmt = $pdo->query("SELECT id FROM tags ORDER BY id ASC");
    while ($row = $stmt->fetch()) {
        $urls[] = [
            'loc' => $base . '/tag.php?id=' . (int)$row['id'],
            'priority' => '0.5',
        ];
    }

    
    $urls[] = [
        'loc' => $base . '/links.php',
        'priority' => '0.4',
    ];
} catch (Throwable $e) {
    
}

echo '<?xml version="1.0" encoding="UTF-8"?>', "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($urls as $u): ?>
    <url>
        <loc><?php echo htmlspecialchars($u['loc'], ENT_QUOTES, 'UTF-8'); ?></loc>
        <?php if (!empty($u['lastmod'])): ?>
        <lastmod><?php echo htmlspecialchars($u['lastmod'], ENT_QUOTES, 'UTF-8'); ?></lastmod>
        <?php endif; ?>
        <?php if (!empty($u['priority'])): ?>
        <priority><?php echo $u['priority']; ?></priority>
        <?php endif; ?>
    </url>
<?php endforeach; ?>
</urlset>
