<?php
/**
 * IPTV Secure Links - XML Sitemap
 * SEO-friendly sitemap for search engines
 */

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

$pages = [
    ['loc' => BASE_URL, 'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => BASE_URL . 'links', 'priority' => '0.9', 'changefreq' => 'hourly'],
    ['loc' => BASE_URL . 'scanner', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['loc' => BASE_URL . 'stats', 'priority' => '0.7', 'changefreq' => 'daily'],
    ['loc' => BASE_URL . 'api-docs', 'priority' => '0.6', 'changefreq' => 'weekly'],
    ['loc' => BASE_URL . 'about', 'priority' => '0.5', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'faq', 'priority' => '0.5', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'contact', 'priority' => '0.5', 'changefreq' => 'monthly'],
    ['loc' => BASE_URL . 'policy', 'priority' => '0.3', 'changefreq' => 'yearly'],
    ['loc' => BASE_URL . 'terms', 'priority' => '0.3', 'changefreq' => 'yearly'],
    ['loc' => BASE_URL . 'sitemap', 'priority' => '0.3', 'changefreq' => 'monthly'],
];

// Add individual link pages
try {
    $stmt = db()->query("SELECT id, created_at FROM iptv_links WHERE status = 'VALID' ORDER BY created_at DESC LIMIT 1000");
    $links = $stmt->fetchAll();

    foreach ($links as $link) {
        $pages[] = [
            'loc' => BASE_URL . 'links?id=' . $link['id'],
            'priority' => '0.6',
            'changefreq' => 'weekly',
            'lastmod' => date('Y-m-d', $link['created_at'])
        ];
    }
} catch (Exception $e) {
    // Silently continue if table doesn't exist
}

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <?php foreach ($pages as $page): ?>
    <url>
        <loc><?= htmlspecialchars($page['loc']) ?></loc>
        <?php if (isset($page['lastmod'])): ?>
        <lastmod><?= $page['lastmod'] ?></lastmod>
        <?php endif; ?>
        <changefreq><?= $page['changefreq'] ?></changefreq>
        <priority><?= $page['priority'] ?></priority>
    </url>
    <?php endforeach; ?>
</urlset>
