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

if (ob_get_length()) ob_clean();

header('Content-Type: text/xml; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$host = 'localhost';
$db   = 'heizweb_animeforum';
$user = 'heizweb_animeforum';
$pass = 'Remower2020';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    echo '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>';
    exit;
}

$baseUrl = 'https://heizweb.ru';

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

// Главная
echo '<url><loc>' . $baseUrl . '/</loc><changefreq>hourly</changefreq><priority>1.0</priority></url>';

// Статические страницы
$staticPages = [
    '/articles/' => 'daily',
    '/rules/'    => 'weekly',
    '/contact/'  => 'monthly',
    '/feed/'     => 'hourly'
];

foreach ($staticPages as $page => $freq) {
    echo '<url><loc>' . $baseUrl . $page . '</loc><changefreq>' . $freq . '</changefreq><priority>0.9</priority></url>';
}

// Новости
$stmt = $pdo->query("SELECT link, published FROM news WHERE new_title != '' ORDER BY id DESC LIMIT 5000");
$news = $stmt->fetchAll();

foreach ($news as $item) {
    if (empty($item['link'])) continue;
    $url = $baseUrl . '/news/' . urlencode(base64_encode($item['link']));
    $date = date('c', strtotime($item['published'] ?? 'now'));
    
    echo '<url>';
    echo '<loc>' . htmlspecialchars($url) . '</loc>';
    echo '<lastmod>' . $date . '</lastmod>';
    echo '<changefreq>daily</changefreq>';
    echo '<priority>0.8</priority>';
    echo '</url>';
}

echo '</urlset>';