<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/constants.php';

header('Content-Type: text/xml; charset=utf-8');

$baseUrl = SITE_URL;

$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

// Pages statiques
$staticPages = [
    ['loc' => $baseUrl . '/', 'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => $baseUrl . '/search', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => $baseUrl . '/login', 'priority' => '0.5', 'changefreq' => 'monthly'],
    ['loc' => $baseUrl . '/register', 'priority' => '0.5', 'changefreq' => 'monthly'],
];

foreach ($staticPages as $page) {
    $xml .= '<url>';
    $xml .= '<loc>' . htmlspecialchars($page['loc']) . '</loc>';
    $xml .= '<changefreq>' . $page['changefreq'] . '</changefreq>';
    $xml .= '<priority>' . $page['priority'] . '</priority>';
    $xml .= '</url>';
}

// Catégories
$categories = $pdo->query("SELECT slug FROM categories WHERE 1=1")->fetchAll(PDO::FETCH_COLUMN);
foreach ($categories as $cat) {
    $xml .= '<url>';
    $xml .= '<loc>' . htmlspecialchars($baseUrl . '/category/' . $cat) . '</loc>';
    $xml .= '<changefreq>weekly</changefreq>';
    $xml .= '<priority>0.7</priority>';
    $xml .= '</url>';
}

// Serveurs actifs
$servers = $pdo->query("SELECT id, updated_at FROM servers WHERE status = 'approved' ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
foreach ($servers as $server) {
    $xml .= '<url>';
    $xml .= '<loc>' . htmlspecialchars($baseUrl . '/server.php?id=' . $server['id']) . '</loc>';
    $xml .= '<lastmod>' . date('c', strtotime($server['updated_at'] ?? 'now')) . '</lastmod>';
    $xml .= '<changefreq>weekly</changefreq>';
    $xml .= '<priority>0.8</priority>';
    $xml .= '</url>';
}

$xml .= '</urlset>';

echo $xml;