<escape><?php
ini_set('display_errors', '0');
error_reporting(0);

require_once __DIR__ . '/includes/bootstrap.php';

$baseUrl = rtrim(SITE_URL, '/');

try {
    $stmt = db()->prepare(
        "SELECT slug, published_at, created_at
         FROM articles
         WHERE status = 'published'
         ORDER BY id DESC"
    );
    $stmt->execute();
    $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    http_response_code(500);
    exit;
}

$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

$urls = [
    ['url' => $baseUrl . '/', 'date' => null]
];

foreach ($articles as $article) {
    if (empty($article['slug'])) {
        continue;
    }

    $urls[] = [
        'url' => $baseUrl . '/makale.php?slug=' . rawurlencode($article['slug']),
        'date' => $article['published_at'] ?: $article['created_at']
    ];
}

foreach ($urls as $item) {
    $xml .= "  <url>\n";
    $xml .= '    <loc>' . htmlspecialchars($item['url'], ENT_XML1 | ENT_QUOTES, 'UTF-8') . "</loc>\n";

    if (!empty($item['date']) && strtotime($item['date'])) {
        $xml .= '    <lastmod>' . date('Y-m-d', strtotime($item['date'])) . "</lastmod>\n";
    }

    $xml .= "  </url>\n";
}

$xml .= "</urlset>\n";

header('Content-Type: application/xml; charset=UTF-8');
header('Content-Length: ' . strlen($xml));

echo $xml;
exit;
?>
</escape>