<?php
error_reporting(0);
ini_set('display_errors', 0);

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/app/Core/Database.php';

use App\Core\Database;

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

$articles = $db->fetchAll("SELECT slug, published_at, last_updated, title FROM articles WHERE status = 'published' ORDER BY published_at DESC");
$categories = $db->fetchAll("SELECT id, name FROM categories WHERE is_active = 1");
$pages = $db->fetchAll("SELECT slug, updated_at FROM pages WHERE status = 'published'");

$baseUrl = 'https://tefisc.com';

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?php echo $baseUrl; ?>/</loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>hourly</changefreq>
        <priority>1.0</priority>
    </url>
    <?php foreach ($categories as $cat): ?>
    <url>
        <loc><?php echo $baseUrl; ?>/category.php?id=<?php echo $cat['id']; ?></loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endforeach; ?>
    <?php foreach ($articles as $article): ?>
    <url>
        <loc><?php echo $baseUrl; ?>/article.php?slug=<?php echo urlencode($article['slug']); ?></loc>
        <lastmod><?php echo date('Y-m-d', strtotime($article['last_updated'] ?? $article['published_at'] ?? 'now')); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>
    <?php endforeach; ?>
    <?php foreach ($pages as $page): ?>
    <url>
        <loc><?php echo $baseUrl; ?>/page.php?slug=<?php echo urlencode($page['slug']); ?></loc>
        <lastmod><?php echo date('Y-m-d', strtotime($page['updated_at'] ?? 'now')); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
    <?php endforeach; ?>
</urlset>
