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

define("APP_SIGNATURE", "raccoonsquare");
include_once("sys/core/init.inc.php");

$dbo = new PDO(DB_DSN, DB_USER, DB_PASSWORD);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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

$base_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];

$static_pages = array(
    array('url' => '/', 'priority' => 1.0, 'changefreq' => 'daily'),
    array('url' => '/signup', 'priority' => 0.9, 'changefreq' => 'daily'),
    array('url' => '/login', 'priority' => 0.9, 'changefreq' => 'daily'),
    array('url' => '/about', 'priority' => 0.7, 'changefreq' => 'monthly'),
    array('url' => '/privacy', 'priority' => 0.6, 'changefreq' => 'monthly'),
    array('url' => '/terms', 'priority' => 0.6, 'changefreq' => 'monthly'),
    array('url' => '/safety', 'priority' => 0.7, 'changefreq' => 'monthly'),
    array('url' => '/support', 'priority' => 0.6, 'changefreq' => 'monthly'),
);

foreach ($static_pages as $page) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($base_url . $page['url']) . "</loc>\n";
    echo "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    echo "    <changefreq>" . $page['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $page['priority'] . "</priority>\n";
    echo "  </url>\n";
}

try {
    $query = $dbo->prepare("SELECT id, username, UNIX_TIMESTAMP(createdAt) as timestamp FROM users WHERE state = ? AND username IS NOT NULL LIMIT 10000");
    $query->execute(array(ACCOUNT_STATE_ENABLED));
    
    while ($user = $query->fetch(PDO::FETCH_ASSOC)) {
        if (!empty($user['username'])) {
            echo "  <url>\n";
            echo "    <loc>" . htmlspecialchars($base_url . "/profile/" . urlencode($user['username'])) . "</loc>\n";
            echo "    <lastmod>" . date('Y-m-d', $user['timestamp']) . "</lastmod>\n";
            echo "    <changefreq>weekly</changefreq>\n";
            echo "    <priority>0.5</priority>\n";
            echo "  </url>\n";
        }
    }
} catch (Exception $e) {
    error_log("Sitemap generation error: " . $e->getMessage());
}

echo '</urlset>';
?>
