<?php
declare(strict_types=1);

/**
 * /sitemap.xml.php
 * Sitemap для VMEREGI:
 * - тільки фінальні canonical URL
 * - без lang-параметрів
 * - без дублів
 * - профілі: /profile/?u=username
 * - групи: тільки не закриті
 */

ob_start();

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

$pdo = db();

$junk = ob_get_contents();
if ($junk !== false && $junk !== '') {
    ob_clean();
}

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

if (!function_exists('h')) {
    function h(?string $s): string {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_XML1, 'UTF-8');
    }
}

function iso_date(?string $dt): string
{
    $s = trim((string)$dt);
    if ($s === '') return date('Y-m-d');
    return substr($s, 0, 10);
}

function add_url(array &$urls, string $loc, string $lastmod, string $changefreq, string $priority): void
{
    $loc = trim($loc);
    if ($loc === '') return;

    $urls[$loc] = [
        'loc'        => $loc,
        'lastmod'    => $lastmod,
        'changefreq' => $changefreq,
        'priority'   => $priority,
    ];
}

$urls = [];
$today = date('Y-m-d');

add_url($urls, abs_url('/'), $today, 'hourly', '1.0');

if (is_file(__DIR__ . '/users.php')) {
    add_url($urls, abs_url('/users.php'), $today, 'daily', '0.8');
}

add_url($urls, abs_url('/group.php'), $today, 'daily', '0.8');

try {
    $st = $pdo->query("
        SELECT
            LOWER(username) AS uname,
            MAX(COALESCE(updated_at, created_at, NOW())) AS lm
        FROM users
        WHERE is_active = 1
          AND username IS NOT NULL AND username <> ''
        GROUP BY LOWER(username)
        ORDER BY lm DESC
    ");

    while ($u = $st->fetch(PDO::FETCH_ASSOC)) {
        $uname = (string)($u['uname'] ?? '');
        if ($uname === '') continue;

        $loc = abs_url('/profile/?u=' . rawurlencode($uname));
        add_url($urls, $loc, iso_date($u['lm'] ?? ''), 'weekly', '0.6');
    }
} catch (Throwable $e) {
    // не валимо sitemap
}

try {
    $st = $pdo->query("
        SELECT slug, MAX(COALESCE(updated_at, created_at, NOW())) AS lm
        FROM groups
        WHERE slug IS NOT NULL AND slug <> ''
          AND (is_closed = 0 OR is_closed IS NULL)
        GROUP BY slug
        ORDER BY lm DESC
    ");

    while ($g = $st->fetch(PDO::FETCH_ASSOC)) {
        $slug = (string)($g['slug'] ?? '');
        if ($slug === '') continue;

        $loc = abs_url('/functional/group/view.php?g=' . rawurlencode($slug));
        add_url($urls, $loc, iso_date($g['lm'] ?? ''), 'weekly', '0.6');
    }
} catch (Throwable $e) {
    // не валимо sitemap
}

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

foreach (array_values($urls) as $u) {
    echo "  <url>\n";
    echo "    <loc>" . h((string)$u['loc']) . "</loc>\n";
    echo "    <lastmod>" . h((string)$u['lastmod']) . "</lastmod>\n";
    echo "    <changefreq>" . h((string)$u['changefreq']) . "</changefreq>\n";
    echo "    <priority>" . h((string)$u['priority']) . "</priority>\n";
    echo "  </url>\n";
}

echo "</urlset>\n";

ob_end_flush();