<?php
header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Expires: 0');
error_reporting(0);

define('SITE_URL', 'https://' . ($_SERVER['HTTP_HOST'] ?? 'sex-videochat.info'));

// If main domain — return sitemap index pointing to all subdomains
$_host = $_SERVER['HTTP_HOST'] ?? 'sex-videochat.info';
if (($_host === 'sex-videochat.info' || $_host === 'www.sex-videochat.info') && !isset($_GET['pages'])) {
    $subdomains = ['en','de','fr','es','it','pt','jp','cn','kr','in'];
    $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "
";
    $xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "
";
    foreach ($subdomains as $sub) {
        $url = $sub === 'en' ? 'https://sex-videochat.info/sitemap-pages.xml' : "https://{$sub}.sex-videochat.info/sitemap.xml";
        $xml .= "  <sitemap><loc>{$url}</loc><lastmod>" . date('Y-m-d') . "</lastmod></sitemap>
";
    }
    $xml .= '</sitemapindex>';
    echo $xml;
    exit;
}

const USER_ID   = '492b59a9925d01876c059022ef32fa6f9949ef373e4179aa08008786798f6032';
const API_KEY   = '22f4ea13b6dd0a08a0d9';
const CACHE_DIR = __DIR__ . '/cache';
const CACHE_TTL = 3600; // 1 hour

// Serve pre-generated cache INSTANTLY — never block Googlebot on the live API.
// cron_sitemaps.php refreshes these files in the background via ?refresh.
$out = CACHE_DIR . '/sitemap_out_' . preg_replace('/[^a-z0-9.]/', '', $_SERVER['HTTP_HOST'] ?? 'default') . '.xml';
$isRefresh = isset($_GET['refresh']) && $_GET['refresh'] === 'rfsh_9b2f';
if (!$isRefresh && file_exists($out)) {
    readfile($out);   // stale-but-instant; cron keeps it fresh
    exit;
}

function fetchModels(string $tag): array {
    $file = CACHE_DIR . '/sit_' . md5($tag) . '.json';
    if (file_exists($file) && (time() - filemtime($file)) < CACHE_TTL) {
        return json_decode(file_get_contents($file), true) ?: [];
    }
    $url = 'https://go.eiscprts.com/app/models-ext/models?' . http_build_query([
        'userId' => USER_ID, 'tag' => $tag, 'limit' => 9999,
    ]);
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . API_KEY],
    ]);
    $body = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($code !== 200 || !$body) return [];
    $d = json_decode($body, true);
    $models = $d['models'] ?? $d['data'] ?? (isset($d[0]) ? $d : []);
    if (!empty($models)) @file_put_contents($file, json_encode($models), LOCK_EX);
    return is_array($models) ? $models : [];
}

// Fetch all 4 base categories
$usernames = [];
$tagCount  = []; // tag => frequency

foreach (['girls', 'men', 'couples', 'trans'] as $cat) {
    foreach (fetchModels($cat) as $m) {
        $u = $m['username'] ?? '';
        if ($u) $usernames[$u] = true;
        foreach ($m['tags'] ?? [] as $tag) {
            // Only tags matching base/slug pattern (no nested slashes)
            if (preg_match('/^(girls|men|couples|trans)\/([a-z0-9][a-z0-9\-]+)$/', $tag)) {
                $tagCount[$tag] = ($tagCount[$tag] ?? 0) + 1;
            }
        }
    }
}

// Sort tags by frequency, take top 200
arsort($tagCount);
$topTags = array_keys(array_slice($tagCount, 0, 200, true));

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

$u = fn(string $loc, string $freq, string $pri) =>
    "  <url><loc>" . SITE_URL . $loc . "</loc><changefreq>{$freq}</changefreq><priority>{$pri}</priority></url>\n";

// Static pages
$xml .= $u('/',         'hourly', '1.0');
$xml .= $u('/girls/',   'hourly', '0.9');
$xml .= $u('/men/',     'hourly', '0.9');
$xml .= $u('/couples/', 'hourly', '0.9');
$xml .= $u('/trans/',   'hourly', '0.9');

// Tag pages (dynamic, sorted by popularity)
$highPri = ['ebony','asian','latin','mature','teens','milfs','bbw','big-tits','anal','squirt','blowjob','masturbation','young','russian','indian'];
foreach ($topTags as $tag) {
    $slug = explode('/', $tag)[1];
    $pri  = in_array($slug, $highPri) ? '0.8' : '0.6';
    $xml .= $u("/{$tag}/", 'daily', $pri);
}

// Model pages
foreach (array_keys($usernames) as $username) {
    $xml .= $u('/model/' . rawurlencode($username), 'daily', '0.5');
}

$xml .= '</urlset>';

@file_put_contents($out, $xml, LOCK_EX);
echo $xml;
