<?php
/* ============================================================
   sitemap.php — gera XML dinâmico do sitemap
   Acessível via /sitemap.xml (com regra nginx) ou /sitemap.php
   ============================================================ */

require_once __DIR__ . '/includes/brands.php';

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

date_default_timezone_set('Europe/Lisbon');
$today = date('Y-m-d');
$site = 'https://reidosbonus.com';

// URLs e prioridades
$urls = [
    // Páginas principais
    ['loc' => '/',           'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => '/casino/',    'priority' => '0.9', 'changefreq' => 'daily'],
    ['loc' => '/apostas/',   'priority' => '0.9', 'changefreq' => 'daily'],
];

// Páginas de marca individuais (só as que têm has_page = true)
foreach ($brands as $slug => $b) {
    foreach (['casino', 'apostas'] as $type) {
        if (!empty($b['has_page'][$type])) {
            $urls[] = [
                'loc' => "/{$type}/{$slug}",
                'priority' => '0.8',
                'changefreq' => 'weekly',
            ];
        }
    }
}

// Cluster pages
$urls[] = ['loc' => '/casino/bonus-sem-deposito', 'priority' => '0.8', 'changefreq' => 'weekly'];
$urls[] = ['loc' => '/casino/free-spins',         'priority' => '0.8', 'changefreq' => 'weekly'];
$urls[] = ['loc' => '/apostas/freebets',          'priority' => '0.8', 'changefreq' => 'weekly'];
$urls[] = ['loc' => '/apostas/aposta-sem-risco',  'priority' => '0.8', 'changefreq' => 'weekly'];

// Landings .html na raiz (deteção automática)
$landings_dir = __DIR__;
foreach (glob($landings_dir . '/*.html') as $file) {
    $filename = basename($file, '.html');
    // Excluir ficheiros que não devem estar no sitemap
    $exclude = ['index', 'age-gate'];
    if (in_array($filename, $exclude)) continue;

    $urls[] = [
        'loc' => '/' . $filename,
        'priority' => '0.6',
        'changefreq' => 'monthly',
        'lastmod' => date('Y-m-d', filemtime($file)),
    ];
}

// Output XML
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as $u) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($site . $u['loc']) . "</loc>\n";
    echo "    <lastmod>" . ($u['lastmod'] ?? $today) . "</lastmod>\n";
    echo "    <changefreq>" . $u['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $u['priority'] . "</priority>\n";
    echo "  </url>\n";
}
echo '</urlset>' . "\n";
