<?php
if (PHP_SAPI === 'cli') {
    $_SERVER['SERVER_PORT'] = $_SERVER['SERVER_PORT'] ?? 443;
    $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'] ?? 'radiostreamers.net';
    $_SERVER['HTTPS'] = $_SERVER['HTTPS'] ?? 'on';
}

require_once __DIR__ . '/../app/config.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/station.php';

const SITEMAP_STATIONS_PER_PAGE = 20000;

function sitemap_escape(string $value): string {
    return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

function sitemap_base_domain(): string {
    return rtrim(APP_DOMAIN, '/');
}

function sitemap_urlset_xml(array $entries): string {
    $xml = [];
    $xml[] = '<?xml version="1.0" encoding="UTF-8"?>';
    $xml[] = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach ($entries as $entry) {
        $xml[] = '<url><loc>' . sitemap_escape($entry['loc']) . '</loc><changefreq>' . sitemap_escape($entry['changefreq']) . '</changefreq><priority>' . sitemap_escape($entry['priority']) . '</priority></url>';
    }
    $xml[] = '</urlset>';
    return implode("\n", $xml) . "\n";
}

function sitemap_index_xml(array $sitemapUrls): string {
    $xml = [];
    $xml[] = '<?xml version="1.0" encoding="UTF-8"?>';
    $xml[] = '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach ($sitemapUrls as $url) {
        $xml[] = '<sitemap><loc>' . sitemap_escape($url) . '</loc></sitemap>';
    }
    $xml[] = '</sitemapindex>';
    return implode("\n", $xml) . "\n";
}

function sitemap_core_entries(): array {
    $domain = sitemap_base_domain();
    $staticUrls = [
        ['path' => '/', 'changefreq' => 'daily', 'priority' => '1.0'],
        ['path' => '/browse', 'changefreq' => 'daily', 'priority' => '0.8'],
        ['path' => '/about', 'changefreq' => 'monthly', 'priority' => '0.4'],
        ['path' => '/contact', 'changefreq' => 'monthly', 'priority' => '0.4'],
        ['path' => '/faq', 'changefreq' => 'monthly', 'priority' => '0.4'],
        ['path' => '/privacy-policy', 'changefreq' => 'yearly', 'priority' => '0.3'],
        ['path' => '/terms-of-service', 'changefreq' => 'yearly', 'priority' => '0.3'],
        ['path' => '/dmca', 'changefreq' => 'yearly', 'priority' => '0.3'],
        ['path' => '/submit-channel', 'changefreq' => 'monthly', 'priority' => '0.5'],
    ];

    $countries = [];
    try {
        $countries = get_countries();
    } catch (Throwable $e) {
    }

    $entries = [];
    foreach ($staticUrls as $url) {
        $loc = $url['path'] === '/' ? $domain . '/' : $domain . $url['path'];
        $entries[] = [
            'loc' => $loc,
            'changefreq' => $url['changefreq'],
            'priority' => $url['priority'],
        ];
    }

    foreach ($countries as $country) {
        $cc = strtoupper((string)($country['country_code'] ?? ''));
        if ($cc === '') {
            continue;
        }
        $entries[] = [
            'loc' => $domain . '/stations/' . rawurlencode($cc),
            'changefreq' => 'weekly',
            'priority' => '0.9',
        ];
    }
    return $entries;
}

function sitemap_station_entries(int $page, int $perPage = SITEMAP_STATIONS_PER_PAGE): array {
    $domain = sitemap_base_domain();
    $offset = max(0, ($page - 1) * $perPage);
    $stations = [];
    try {
        $stmt = db()->prepare("SELECT country_code, enc_lid, lid, name FROM stations WHERE status = 1 ORDER BY votes DESC, clicks DESC, id LIMIT :limit OFFSET :offset");
        $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        $stations = $stmt->fetchAll();
    } catch (Throwable $e) {
    }

    $entries = [];
    foreach ($stations as $station) {
        $cc = strtoupper((string)($station['country_code'] ?? ''));
        $encLid = trim((string)($station['enc_lid'] ?? ''));
        if ($encLid === '' && !empty($station['lid'])) {
            $encLid = encode_lid((int)$station['lid']);
        }
        if ($cc === '' || $encLid === '') {
            continue;
        }
        $slug = make_slug((string)($station['name'] ?? ''));
        if ($slug === '') {
            $slug = 'radio';
        }
        $entries[] = [
            'loc' => $domain . '/play/' . rawurlencode($cc) . '/' . rawurlencode($encLid) . '/' . rawurlencode($slug),
            'changefreq' => 'monthly',
            'priority' => '0.7',
        ];
    }
    return $entries;
}

function sitemap_station_pages(int $perPage = SITEMAP_STATIONS_PER_PAGE): int {
    try {
        $count = (int)db()->query("SELECT COUNT(*) FROM stations WHERE status = 1")->fetchColumn();
    } catch (Throwable $e) {
        $count = 0;
    }
    return max(1, (int)ceil($count / $perPage));
}

function sitemap_build_index(): string {
    $domain = sitemap_base_domain();
    $pages = sitemap_station_pages();
    $sitemapUrls = [];
    $sitemapUrls[] = $domain . '/sitemap.xml?part=core';
    for ($i = 1; $i <= $pages; $i++) {
        $sitemapUrls[] = $domain . '/sitemap.xml?part=stations&page=' . $i;
    }
    return sitemap_index_xml($sitemapUrls);
}

function sitemap_build_part(string $part, int $page): string {
    if ($part === 'core') {
        return sitemap_urlset_xml(sitemap_core_entries());
    }
    if ($part === 'stations') {
        return sitemap_urlset_xml(sitemap_station_entries(max(1, $page)));
    }
    return sitemap_build_index();
}

if (PHP_SAPI === 'cli') {
    $options = getopt('', ['output::', 'stdout', 'part::', 'page::']);
    $part = (string)($options['part'] ?? '');
    $page = max(1, (int)($options['page'] ?? 1));
    $xml = $part === '' ? sitemap_build_index() : sitemap_build_part($part, $page);
    if (isset($options['stdout'])) {
        echo $xml;
        exit(0);
    }
    $outputPath = $options['output'] ?? (__DIR__ . '/sitemap.xml');
    file_put_contents($outputPath, $xml);
    echo "Sitemap generated at: {$outputPath}\n";
    exit(0);
}

$part = (string)($_GET['part'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$xml = $part === '' ? sitemap_build_index() : sitemap_build_part($part, $page);

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