<?php
error_reporting(0);
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);

while (ob_get_level()) { ob_end_clean(); }
ob_start();

header('Content-Type: text/xml; charset=utf-8');
header('Cache-Control: no-cache');
ob_clean();

// ─── Config ─────────────────────────────────────────────────────────────────
define('ITEMS_PER_SITEMAP', 5000);
define('TOTAL_URLS', 50000);

// ─── Base URL ────────────────────────────────────────────────────────────────
function getBaseUrl() {
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
    $scriptPath = dirname($_SERVER['SCRIPT_NAME']);
    $basePath = ($scriptPath === '/' || $scriptPath === '\\') ? '' : $scriptPath;
    return 'https://' . $host . $basePath;
}
define('BASE_URL', getBaseUrl());

// ─── Keywords dari keyword1.txt (untuk random URL) ─────────────────────────────
function &_keywords(): array {
    static $kw;
    if (isset($kw)) return $kw;
    $kw = array();
    $file = __DIR__ . '/keyword1.txt';
    if (is_readable($file)) {
        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if ($lines !== false) {
            foreach ($lines as $line) {
                $slug = trim(strtolower($line));
                $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
                $slug = trim($slug, '-');
                if ($slug !== '') $kw[] = $slug;
            }
        }
    }
    if (empty($kw)) $kw = array('keyword', 'video', 'info', 'page', 'content');
    return $kw;
}

// ─── Random Word Pool (untuk random URL) ─────────────────────────────────────
function &_randomPool(): array {
    static $p;
    if (isset($p)) return $p;

    $p['nouns'] = array(
        'collections', 'products', 'articles', 'stories', 'gallery',
        'photos', 'videos', 'posts', 'topics', 'categories',
        'guides', 'reviews', 'profiles', 'archives', 'downloads',
        'media', 'resources', 'pages', 'entries', 'records',
        'news', 'blog', 'docs', 'wiki', 'tags',
        'search', 'explore', 'discover', 'browse', 'trending',
        'popular', 'latest', 'featured', 'highlights', 'picks',
        'shop', 'store', 'deals', 'offers', 'promo',
        'community', 'forum', 'groups', 'users', 'members',
        'events', 'live', 'shows', 'series', 'episodes',
    );
    $p['adjectives'] = array(
        'best', 'top', 'new', 'hot', 'free',
        'full', 'real', 'raw', 'hd', 'premium',
        'viral', 'trending', 'popular', 'fresh', 'daily',
        'weekly', 'monthly', 'exclusive', 'official', 'original',
        'unlimited', 'ultimate', 'complete', 'super', 'mega',
        'fast', 'smart', 'easy', 'safe', 'trusted',
        'verified', 'certified', 'pro', 'lite', 'mini',
        'old', 'classic', 'retro', 'modern', 'advanced',
        'simple', 'basic', 'standard', 'extra', 'special',
        'private', 'public', 'open', 'closed', 'hidden',
    );
    $p['topics'] = array(
        'fashion', 'lifestyle', 'health', 'fitness', 'travel',
        'food', 'cooking', 'music', 'sports', 'gaming',
        'tech', 'science', 'nature', 'art', 'culture',
        'education', 'finance', 'business', 'politics', 'law',
        'design', 'photography', 'film', 'books', 'poetry',
        'animals', 'pets', 'garden', 'home', 'decor',
        'beauty', 'makeup', 'skincare', 'hair', 'wellness',
        'family', 'parenting', 'kids', 'baby', 'teens',
        'dating', 'relationship', 'marriage', 'love', 'friendship',
        'car', 'bike', 'auto', 'transport', 'adventure',
    );
    $p['slugs'] = array(
        'guide', 'tips', 'tricks', 'hacks', 'secrets',
        'ideas', 'inspiration', 'tutorial', 'howto', 'review',
        'overview', 'summary', 'analysis', 'comparison', 'ranking',
        'list', 'roundup', 'spotlight', 'feature', 'story',
        'update', 'news', 'report', 'info', 'detail',
        'intro', 'basics', 'advanced', 'masterclass', 'course',
        'checklist', 'template', 'example', 'sample', 'demo',
        'solution', 'answer', 'faq', 'help', 'support',
        'plan', 'strategy', 'method', 'approach', 'framework',
        'collection', 'library', 'database', 'index', 'directory',
    );
    $p['ids'] = array(
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
        '100', '101', '200', '201', '300', '404', '500',
        'a1', 'b2', 'c3', 'd4', 'e5', 'f6', 'g7', 'h8',
        '2024', '2025', '2026', 'v1', 'v2', 'v3',
    );
    $p['alpha'] = array(
        'a','b','c','d','e','f','g','h','i','j','k','l','m',
        'n','o','p','q','r','s','t','u','v','w','x','y','z',
    );
    $p['short_nums'] = array(
        '1','2','3','4','5','6','7','8','9','10',
    );
    return $p;
}

function pickWord(string $pool_key, string $seed): string {
    $p =& _randomPool();
    $arr = $p[$pool_key];
    return $arr[abs(crc32($seed)) % count($arr)];
}

function pickKeyword(string $seed): string {
    $kw =& _keywords();
    return $kw[abs(crc32($seed)) % count($kw)];
}

// ─── Word Builder: rakit kata sendiri dari suku kata (konsonan+vokal) ────────
// Menghasilkan kata unik per seed, bukan dari pool statis.
// Contoh output: "trikov", "zelpa", "bandur", "xemoli", dll.
function buildWord(string $seed, int $syllables = 0): string {
    $cons = array('b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','w','x','z');
    $vows = array('a','e','i','o','u');
    $nc   = count($cons);
    $nv   = count($vows);

    // jumlah suku kata: 2–4 (acak tapi deterministik)
    if ($syllables < 1) {
        $syllables = 2 + (abs(crc32($seed . 'syl')) % 3); // 2, 3, atau 4
    }

    $word = '';
    for ($s = 0; $s < $syllables; $s++) {
        // Setiap suku kata: konsonan + vokal (+ kadang konsonan penutup)
        $word .= $cons[abs(crc32($seed . 'c' . $s)) % $nc];
        $word .= $vows[abs(crc32($seed . 'v' . $s)) % $nv];
        // 30% peluang konsonan penutup di akhir suku kata
        if (abs(crc32($seed . 'cl' . $s)) % 10 < 3) {
            $word .= $cons[abs(crc32($seed . 'cx' . $s)) % $nc];
        }
    }
    return $word;
}

// Versi dua kata dipisah tanda hubung: "trikov-zelpa"
function buildSlug(string $seed): string {
    return buildWord($seed . 'A') . '-' . buildWord($seed . 'B');
}

// ─── Static Pool ─────────────────────────────────────────────────────────────
function &_indoPool(): array {
    static $p;
    if (isset($p)) return $p;

    $p['base'] = array(
        'xnxx', 'eporner', 'pornhub', 'xvideos', 'redtube', 'youporn',
        'brazzers', 'bangbros', 'naughtyamerica', 'realitykings',
        'mofos', 'teamskeet', 'onlyfans', 'stripchat', 'chaturbate',
        'spankbang', 'drtuber', 'tube8', 'beeg', 'hclips',
        'xhamster', 'youjizz', 'tnaflix', 'sunporno', 'txxx',
        'nuvid', 'tubegalore', 'pornone', 'fuq', 'lobstertube',
        'thumbzilla', 'porntrex', 'sxyprn', 'daftsex', 'porndoe',
        'faphouse', 'sexvid', 'cam4', 'bongacams', 'porn300',
        'bokep', 'bokepindo', 'bokepjepang', 'bokepviral', 'bokepterbaru',
        'bokepabg', 'bokepbarat', 'bokepkorea', 'bokeplive', 'bokeptiktok',
        'videomesum', 'videopanas', 'filmsemi', 'filmbokep', 'ngentot',
        'nontonbokep', 'downloadbokep', 'streamingbokep', 'linkbokep',
        'bokenindo', 'semprot', 'lendir', 'colmek', 'memek',
        'simontok', 'indoxxi', 'layarkaca', 'ganool',
        'video', 'stream', 'download', 'watch', 'play', 'nonton',
        'gratis', 'terbaru', 'viral', 'link', 'live', 'hot',
        'full', 'free', 'premium', 'uncensored', 'raw', 'hd',
        'indo', 'japan', 'jepang', 'korea', 'barat', 'asia',
        'thai', 'melayu', 'china', 'arab', 'pinoy', 'malay',
        'jav', 'hentai', 'doujin', 'manga', 'anime', 'cosplay',
        'amateur', 'homemade', 'webcam', 'camgirl', 'livecam',
        'fanza', 'dmm', 'mgs', 'sokmil', 'r18',
        'crot', 'genjot', 'desah', 'goyang', 'enak', 'mantap',
        'nikmat', 'puas', 'sange', 'tegang', 'basah', 'becek',
        'twitter', 'telegram', 'tiktok', 'whatsapp', 'instagram',
        'facebook', 'bigo', 'mango', 'michat', 'ometv', 'tantan',
        'mahasiswi', 'perawat', 'guru', 'pns', 'ojol', 'spg',
        'artis', 'selebgram', 'tiktoker', 'model', 'biduan',
        'hijab', 'jilbab', 'abg', 'tante', 'janda', 'milf',
    );

    $p['level2'] = array('video', 'clips', 'stream', 'watch', 'play', 'media');

    $p['phrases'] = array(
        'sex-videos', 'bokep-indo', 'bokep-viral', 'bokep-terbaru', 'video-panas',
        'film-semi', 'film-bokep', 'video-mesum', 'nonton-bokep', 'download-bokep',
        'streaming-bokep', 'bokep-jepang', 'bokep-barat', 'bokep-korea', 'bokep-thailand',
        'bokep-hijab', 'bokep-jilbab', 'bokep-abg', 'bokep-tante', 'bokep-janda',
        'bokep-mahasiswi', 'bokep-perawat', 'bokep-guru', 'bokep-ojol', 'bokep-hotel',
        'bokep-live', 'bokep-tiktok', 'bokep-twitter', 'bokep-telegram', 'video-viral',
        'sex-arab', 'sex-japan', 'sex-korea', 'sex-india', 'sex-melayu',
        'video-dewasa', 'video-18plus', 'film-dewasa', 'konten-dewasa',
        'jav-uncensored', 'jav-sub-indo', 'jav-hd', 'jav-terbaru',
        'hentai-sub-indo', 'manga-dewasa', 'doujin-indo',
        'live-streaming', 'cam-girl', 'bigo-live', 'mango-live',
        'gf-bf-sex', 'desi-sex', 'hindi-sex', 'tamil-sex', 'bangla-sex',
        'pinay-sex', 'malay-sex', 'thai-sex', 'indo-sex', 'asian-sex',
        'amateur-homemade', 'real-amateur', 'leaked-video', 'skandal-viral',
    );

    $p['brands'] = array(
        'xnxx', 'xvideos', 'pornhub', 'xhamster', 'redtube', 'youporn',
        'brazzers', 'bangbros', 'realitykings', 'teamskeet',
        'spankbang', 'tube8', 'beeg', 'youjizz', 'txxx',
        'stripchat', 'chaturbate', 'onlyfans', 'cam4',
        'simontok', 'layarkaca', 'indoxxi', 'semprot',
    );

    $p['lang'] = array(
        'indo', 'hindi', 'arab', 'japan', 'korea', 'thai', 'melayu',
        'china', 'pinay', 'desi', 'tamil', 'bangla', 'malay', 'turkish',
        'vietnamese', 'myanmar', 'cambodia', 'laos', 'nepal', 'srilanka',
    );

    return $p;
}

// ─── Helper Functions ────────────────────────────────────────────────────────

function mutateWord($word, $seed) {
    $chars = str_split(strtolower($word));
    $len = count($chars);
    if ($len === 0) return $word;
    $mutated = '';
    foreach ($chars as $i => $c) {
        $mutated .= $c;
        if (abs(crc32($seed . 'rep' . $i)) % 10 < 3) {
            $mutated .= str_repeat($c, 1 + (abs(crc32($seed . 'rc' . $i)) % 2));
        }
    }
    return $mutated;
}

function generateFilename($seed) {
    $p =& _indoPool();
    $base    = $p['base'];    $nb = count($base);
    $phrases = $p['phrases']; $np = count($phrases);
    $brands  = $p['brands'];  $nbr = count($brands);
    $lang    = $p['lang'];    $nl = count($lang);

    $parts = array();

    if (abs(crc32($seed . 'haslang')) % 5 < 3) {
        $parts[] = $lang[abs(crc32($seed . 'lang')) % $nl];
    }

    if (abs(crc32($seed . 'hasnum')) % 5 < 2) {
        $nums = array('18', '69', '21', (string)(abs(crc32($seed . 'npfx')) % 99 + 1));
        $parts[] = $nums[abs(crc32($seed . 'nsel')) % 4];
    }

    $phraseCount = 1 + (abs(crc32($seed . 'phcnt')) % 2);
    for ($pp = 0; $pp < $phraseCount; $pp++) {
        $parts[] = $phrases[abs(crc32($seed . 'ph' . $pp)) % $np];
    }

    $brandCount = 2 + (abs(crc32($seed . 'brcnt')) % 3);
    for ($b = 0; $b < $brandCount; $b++) {
        $brand = $brands[abs(crc32($seed . 'br' . $b)) % $nbr];
        switch (abs(crc32($seed . 'brvar' . $b)) % 5) {
            case 0: $parts[] = mutateWord($brand, $seed . 'brm' . $b) . (abs(crc32($seed . 'brn' . $b)) % 100); break;
            case 1: $parts[] = $brand . $brands[abs(crc32($seed . 'br2' . $b)) % $nbr] . (abs(crc32($seed . 'brn2' . $b)) % 100); break;
            case 2: $parts[] = strtolower($brand[0]) . strtoupper(substr($brand, 1)) . '_tv'; break;
            case 3: $parts[] = mutateWord($brand, $seed . 'brm3' . $b); break;
            case 4: $parts[] = substr($brand, 0, 3) . (abs(crc32($seed . 'brn4' . $b)) % 100) . 'x' . ((abs(crc32($seed . 'brsf' . $b)) % 2 === 0) ? 'hub' : 'tube'); break;
        }
    }

    $parts[] = (string)(abs(crc32($seed . 'endnum')) % 99999 + 1);

    $filename = implode('-', $parts);
    $filename = preg_replace('/[^a-zA-Z0-9_\-]/', '', $filename);
    $filename = preg_replace('/-{2,}/', '-', $filename);
    return trim($filename, '-');
}

function generateUrlIndo($i) {
    static $host, $baseUrl;
    if (!isset($host)) {
        $host    = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
        $baseUrl = rtrim(BASE_URL, '/');
    }
    $p     =& _indoPool();
    $seed  = $host . '|indo|' . $i;
    $pfx   = buildWord($seed . 'pfx', 2); // prefix unik per URL, 2 suku kata
    $l2    = $p['level2'][abs(crc32($seed . 'l2')) % 6];
    $fname = generateFilename($seed);
    return $baseUrl . '/' . $pfx . '/' . $l2 . '/' . $fname . '.html';
}

function generateUrlRandom($i) {
    static $baseUrl;
    if (!isset($baseUrl)) {
        $baseUrl = rtrim(BASE_URL, '/');
    }
    $host    = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    $seed    = $host . '|rnd|' . $i;

    // Kata dari pool (statis)
    $w1 = pickWord('nouns',      $seed . 'w1');
    $w2 = pickWord('adjectives', $seed . 'w2');
    $w3 = pickWord('topics',     $seed . 'w3');
    $w4 = pickWord('slugs',      $seed . 'w4');
    $w5 = pickWord('topics',     $seed . 'w5');
    $w6 = pickWord('ids',        $seed . 'w6');
    $kw1 = pickKeyword($seed . 'kw1');
    $kw2 = pickKeyword($seed . 'kw2');
    $maybeId = (abs(crc32($seed . 'hasid')) % 3 === 0) ? '-' . $w6 : '';

    // Huruf tunggal & angka pendek
    $alpha = pickWord('alpha',      $seed . 'al1');
    $snum  = pickWord('short_nums', $seed . 'sn1');

    // Kata hasil BUILD sendiri (unik per URL, bukan dari pool statis)
    $bw1 = buildWord($seed . 'bw1');         // mis: "trikov"
    $bw2 = buildWord($seed . 'bw2');         // mis: "zelpa"
    $bw3 = buildWord($seed . 'bw3');         // mis: "bandur"
    $bs1 = buildSlug($seed . 'bs1');         // mis: "trikov-zelpa"
    $bs2 = buildSlug($seed . 'bs2');         // mis: "fando-xumel"

    // 30 pola: 0-13 pola lama (pool statis), 14-21 huruf/angka, 22-29 build kata sendiri
    $pattern = abs(crc32($seed . 'pat')) % 30;

    switch ($pattern) {
        // ── pool statis ──
        case 0:  return $baseUrl . '/' . $w1;
        case 1:  return $baseUrl . '/' . $w3 . $maybeId . '.html';
        case 2:  return $baseUrl . '/' . $w1 . '/' . $w3;
        case 3:  return $baseUrl . '/' . $w1 . '/' . $w4 . $maybeId . '.html';
        case 4:  return $baseUrl . '/' . $w2 . '/' . $w1 . '/' . $w3;
        case 5:  return $baseUrl . '/' . $w2 . '/' . $w1 . '/' . $w4 . $maybeId . '.html';
        case 6:  return $baseUrl . '/' . $w3 . '-' . $w4 . $maybeId;
        case 7:  return $baseUrl . '/' . $w3 . '-' . $w4 . $maybeId . '.html';
        case 8:  return $baseUrl . '/' . $w1 . '/' . $w5 . '-' . $w4 . $maybeId . '.html';
        case 9:  return $baseUrl . '/' . $w1 . '/' . $w2 . '/' . $w5 . '-' . $w4 . $maybeId . '.html';
        case 10: return $baseUrl . '/' . $kw1 . $maybeId . '.html';
        case 11: return $baseUrl . '/' . $w1 . '/' . $kw1 . $maybeId . '.html';
        case 12: return $baseUrl . '/' . $kw1 . '/' . $w4 . $maybeId . '.html';
        case 13: return $baseUrl . '/' . $w1 . '/' . $kw2 . '-' . $w4 . $maybeId . '.html';
        // ── huruf a-z / angka 1-10 ──
        case 14: return $baseUrl . '/' . $w3 . '-' . $w4 . '-' . $alpha . '.html';
        case 15: return $baseUrl . '/' . $alpha . '/' . $w3 . '-' . $w4 . '.html';
        case 16: return $baseUrl . '/' . $w1 . '/' . $alpha . '/' . $w4 . '.html';
        case 17: return $baseUrl . '/' . $alpha . '-' . $w3 . '-' . $w4 . '.html';
        case 18: return $baseUrl . '/' . $w3 . '/' . $alpha . '-' . $w4 . '.html';
        case 19: return $baseUrl . '/' . $w3 . '-' . $w4 . '-' . $snum . '.html';
        case 20: return $baseUrl . '/' . $snum . '/' . $w3 . '-' . $w4 . '.html';
        case 21: return $baseUrl . '/' . $w1 . '/' . $w3 . '-' . $snum . '.html';
        // ── kata BUILD sendiri (unik per URL) ──
        case 22: return $baseUrl . '/' . $bw1 . '.html';                              // trikov.html
        case 23: return $baseUrl . '/' . $bs1 . '.html';                              // trikov-zelpa.html
        case 24: return $baseUrl . '/' . $bw1 . '/' . $bw2 . '.html';                // trikov/zelpa.html
        case 25: return $baseUrl . '/' . $bw1 . '/' . $bs2 . '.html';                // trikov/fando-xumel.html
        case 26: return $baseUrl . '/' . $w1  . '/' . $bs1 . '.html';                // posts/trikov-zelpa.html
        case 27: return $baseUrl . '/' . $bw1 . '/' . $w4  . '-' . $bw2 . '.html';  // trikov/guide-zelpa.html
        case 28: return $baseUrl . '/' . $alpha . '/' . $bs1 . '.html';              // a/trikov-zelpa.html
        case 29: return $baseUrl . '/' . $bw1 . '-' . $snum . '.html';               // trikov-3.html
        default: return $baseUrl . '/' . $bw1 . '.html';
    }
}

// ─── Combined: pilih acak antara indo-style dan random-style ─────────────────
function generateUrl($i) {
    $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    $seed = $host . '|combined|' . $i;
    // Pilih secara deterministik berdasarkan seed: 0 = indo, 1 = random
    if (abs(crc32($seed . 'pick')) % 2 === 0) {
        return generateUrlIndo($i);
    } else {
        return generateUrlRandom($i);
    }
}

// ─── Sitemap Output ─────────────────────────────────────────────────────────

function generateSitemapIndex($totalUrls) {
    $totalPages = ceil($totalUrls / ITEMS_PER_SITEMAP);
    $lastmod    = date('Y-m-d');
    $baseUrl    = rtrim(BASE_URL, '/');

    ob_clean();
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    for ($i = 1; $i <= $totalPages; $i++) {
        $loc = htmlspecialchars($baseUrl . '/sitemap_indo' . $i . '.xml', ENT_XML1, 'UTF-8');
        echo "  <sitemap><loc>{$loc}</loc><lastmod>{$lastmod}</lastmod></sitemap>\n";
    }
    echo '</sitemapindex>' . "\n";
    ob_end_flush();
    exit;
}

function generateSitemap($page) {
    $offset = ($page - 1) * ITEMS_PER_SITEMAP;
    $count  = min(ITEMS_PER_SITEMAP, TOTAL_URLS - $offset);
    if ($count <= 0) {
        header("HTTP/1.1 404 Not Found");
        exit('Sitemap tidak ditemukan');
    }

    $lastmod = date('Y-m-d');

    ob_clean();
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    for ($i = $offset; $i < $offset + $count; $i++) {
        $loc = htmlspecialchars(generateUrl($i), ENT_XML1, 'UTF-8');
        echo "  <url><loc>{$loc}</loc><lastmod>{$lastmod}</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></url>\n";
    }
    echo '</urlset>' . "\n";
    ob_end_flush();
    exit;
}

// ─── Main ────────────────────────────────────────────────────────────────────
try {
    ob_clean();

    if (isset($_GET['index'])) {
        generateSitemapIndex(TOTAL_URLS);
    }

    if (isset($_GET['page'])) {
        $page = intval($_GET['page']);
        if ($page < 1) {
            ob_clean();
            header("HTTP/1.1 404 Not Found");
            exit('Page tidak valid');
        }
        $totalPages = ceil(TOTAL_URLS / ITEMS_PER_SITEMAP);
        if ($page > $totalPages) {
            ob_clean();
            header("HTTP/1.1 404 Not Found");
            exit('Page tidak ditemukan');
        }
        generateSitemap($page);
    }

    generateSitemapIndex(TOTAL_URLS);

} catch (Exception $e) {
    ob_clean();
    header("HTTP/1.1 500 Internal Server Error");
    header('Content-Type: text/plain; charset=utf-8');
    exit('Error generating sitemap');
}
