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

// Конфигурация API
$API_BASE_URL = 'https://bngprm.com/api/v2';
$CAMPAIGN_ID = 15898;

// Функция для получения IP клиента
function getClientIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    }
}

// Функция для получения онлайн моделей
function getOnlineModels() {
    global $API_BASE_URL, $CAMPAIGN_ID;
    
    try {
        $params = [
            'c' => $CAMPAIGN_ID,
            'client_ip' => getClientIP(),
            'limit' => 5000
        ];
        
        $url = $API_BASE_URL . '/models-online?' . http_build_query($params);
        
        $options = [
            'http' => [
                'timeout' => 10,
                'ignore_errors' => true,
                'header' => "User-Agent: Mozilla/5.0\r\n"
            ]
        ];
        
        $context = stream_context_create($options);
        $response = @file_get_contents($url, false, $context);
        
        if ($response === FALSE) {
            // Если не получилось, пробуем без параметров
            $url = $API_BASE_URL . '/models-online?c=' . $CAMPAIGN_ID;
            $response = @file_get_contents($url, false, $context);
        }
        
        if ($response === FALSE) {
            return [];
        }
        
        $data = @json_decode($response, true);
        
        if ($data && isset($data['models']) && is_array($data['models'])) {
            return $data['models'];
        }
        
    } catch (Exception $e) {
        // Игнорируем ошибки, возвращаем пустой массив
    }
    
    return [];
}

// Получаем модели
$models = getOnlineModels();

// Базовый URL сайта
$baseUrl = 'https://slutnetki.online';
$currentDate = date('Y-m-d\TH:i:s+00:00');

// Статические страницы
$staticPages = [
    '/' => [
        'priority' => '1.0',
        'changefreq' => 'hourly'
    ],
    '/privacy.html' => [
        'priority' => '0.5',
        'changefreq' => 'monthly'
    ],
    '/terms.html' => [
        'priority' => '0.5',
        'changefreq' => 'monthly'
    ],
    '/disclaimer.html' => [
        'priority' => '0.5',
        'changefreq' => 'monthly'
    ],
    '/contact.html' => [
        'priority' => '0.6',
        'changefreq' => 'monthly'
    ]
];

// Генерируем XML
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    
    <!-- Статические страницы -->
    <?php foreach ($staticPages as $url => $props): ?>
    <url>
        <loc><?= htmlspecialchars($baseUrl . $url) ?></loc>
        <lastmod><?= $currentDate ?></lastmod>
        <changefreq><?= $props['changefreq'] ?></changefreq>
        <priority><?= $props['priority'] ?></priority>
    </url>
    <?php endforeach; ?>
    
    <!-- Страницы моделей -->
    <?php if (!empty($models)): ?>
        <?php foreach ($models as $model): ?>
            <?php if (!empty($model['username'])): ?>
    <url>
        <loc><?= htmlspecialchars($baseUrl . '/chat/' . $model['username']) ?></loc>
        <lastmod><?= $currentDate ?></lastmod>
        <changefreq><?= (!empty($model['is_online']) && $model['is_online']) ? 'hourly' : 'daily' ?></changefreq>
        <priority><?= (!empty($model['is_online']) && $model['is_online']) ? '0.9' : '0.7' ?></priority>
    </url>
            <?php endif; ?>
        <?php endforeach; ?>
    <?php endif; ?>
    
</urlset>