<?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();

define('ITEMS_PER_SITEMAP', 5000);
define('KW_FILE', __DIR__ . '/keyword1.txt');

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());

function countKwLines() {
    // Pakai .count file dari buildKwIdx() jika ada (zero-cost, tulis sekali oleh index.php)
    $cntFile = KW_FILE . '.count';
    if (is_file($cntFile) && filemtime($cntFile) >= filemtime(KW_FILE)) {
        $n = (int)@file_get_contents($cntFile);
        if ($n > 0) return $n;
    }
    // Fallback: scan file (hanya terjadi sebelum index.php pernah diakses)
    $fh = @fopen(KW_FILE, 'rb');
    if (!$fh) return 0;
    $n = 0;
    while (!feof($fh)) { $n += substr_count(fread($fh, 65536), "\n"); }
    fclose($fh);
    return $n ?: 1;
}

function getBrandKey($brand) {
    return mb_strtolower(trim($brand), 'UTF-8');
}

function getUrlFormat($brand, $baseUrl) {
    $hash = abs(crc32($baseUrl . '|' . getBrandKey($brand)));
    static $formats;
    if (!isset($formats)) { $formats = array(
        array('type' => 'path', 'param' => ''),
        array('type' => 'html', 'param' => ''),
        array('type' => 'get',  'param' => 'products'),
        array('type' => 'get',  'param' => 'category'),
        array('type' => 'get',  'param' => 'index'),
    ); }
    return $formats[$hash % 5];
}

function getHtmlSlug($brand) {
    static $host;
    if (!isset($host)) $host = parse_url(BASE_URL, PHP_URL_HOST);
    $brandSlug  = str_replace(' ', '-', mb_strtolower(trim($brand), 'UTF-8'));
    $domainSeed = $host . '|' . $brandSlug;
    static $words;
    if (!isset($words)) { $words = array(
        'xnxx','eporner','pornhub','xvideos','redtube','youporn',
        'brazzers','bangbros','naughtyamerica','realitykings',
        'mofos','digitalplayground','teamskeet','wicked','kink',
        'onlyfans','stripchat','chaturbate','bongacams','cam4',
        'spankbang','drtuber','slutload','tube8','extrabig',
        'beeg','hclips','faphouse','sexvid','porn300',
        'xhamster','youjizz','tnaflix','sunporno','txxx',
        'nuvid','tubegalore','pornone','fuq','lobstertube',
        'thumbzilla','porntrex','sxyprn','daftsex','porndoe',
        'lk21','bokep jepang','bokep indo','bokep viral','bokep terbaru',
        'bokep sma','bokep abg','bokep barat','bokep korea','bokep thailand',
        'bokep live','bokep tiktok','video mesum','video syur','video panas',
        'ngentot','guru','viral sma','film semi','film bokep',
        'nonton bokep','download bokep','streaming bokep',
        'bokep twitter','bokep telegram','bokep hot','situs bokep','link bokep',
        'bokep mahasiswa','bokep jilbab','bokep ojol','bokep pelakor','bokep selingkuh',
        'bokep warung','bokep hotel','bokep rumahan','bokep amatir','bokep profesional',
        'bokep full movie','bokep uncensored','bokep hd','bokep 4k','bokep sub indo',
        'bokep cosplay','bokep pijat','bokep kamar mandi','bokep kantor','bokep spg',
        'bokep artis','bokep selebgram','bokep youtuber','bokep tiktoker','bokep influencer',
        'video viral','video trending','video dewasa','video 18+','video premium',
        'video eksklusif','video terbatas','video privat','video leaked','video skandal',
        'film dewasa','film 18+','film panas','film erotis','film blue',
        'jav','jav uncensored','jav sub indo','jav hd','jav terbaru',
        'hentai','hentai sub indo','manga dewasa','doujin','komik hentai',
        'live streaming','live show','cam girl','webcam','bigo live',
    ); }
    $wordCount = 2 + (abs(crc32($domainSeed . 'count')) % 2);
    $parts = array($brandSlug);
    for ($i = 0; $i < $wordCount; $i++) {
        $w = $words[abs(crc32($domainSeed . 'word' . $i)) % 128];
        $parts[] = str_replace(' ', '-', mb_strtolower($w, 'UTF-8'));
    }
    return trim(preg_replace('/-{2,}/', '-', implode('-', $parts)), '-');
}

function outputIndex($total, $baseUrl) {
    $pages   = max(1, ceil($total / ITEMS_PER_SITEMAP));
    $lastmod = date('Y-m-d');
    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 <= $pages; $i++) {
        $loc = htmlspecialchars($baseUrl . '/sitemap' . $i . '.xml', ENT_XML1, 'UTF-8');
        echo "  <sitemap><loc>{$loc}</loc><lastmod>{$lastmod}</lastmod></sitemap>\n";
    }
    echo '</sitemapindex>' . "\n";
}

function outputPage($page, $total, $baseUrl) {
    if ($page < 1 || $total === 0) { header('HTTP/1.1 404 Not Found'); exit('Halaman tidak ditemukan'); }
    $pages = ceil($total / ITEMS_PER_SITEMAP);
    if ($page > $pages) { header('HTTP/1.1 404 Not Found'); exit('Halaman tidak ditemukan'); }

    $offset  = ($page - 1) * ITEMS_PER_SITEMAP;
    $lastmod = date('Y-m-d');

    $fh = @fopen(KW_FILE, 'r');
    if (!$fh) { header('HTTP/1.1 500 Internal Server Error'); exit('keyword1.txt tidak dapat dibaca'); }

    for ($i = 0; $i < $offset && !feof($fh); $i++) fgets($fh);

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

    $count = 0;
    while ($count < ITEMS_PER_SITEMAP && ($line = fgets($fh)) !== false) {
        $brand = trim($line);
        if ($brand === '') continue;
        $slug         = rawurlencode(str_replace(' ', '-', mb_strtolower($brand, 'UTF-8')));
        $encodedBrand = rawurlencode($brand);
        $format       = getUrlFormat($brand, $baseUrl);
        if ($format['type'] === 'path') {
            $loc = $baseUrl . '/' . $slug;
        } elseif ($format['type'] === 'html') {
            $loc = $baseUrl . '/' . rawurlencode(getHtmlSlug($brand)) . '.html';
        } else {
            $loc = $baseUrl . '/?' . $format['param'] . '=' . $encodedBrand;
        }
        echo '  <url><loc>' . htmlspecialchars($loc, ENT_XML1, 'UTF-8') . '</loc>';
        echo '<lastmod>' . $lastmod . '</lastmod>';
        echo '<changefreq>weekly</changefreq><priority>0.8</priority></url>' . "\n";
        $count++;
    }

    fclose($fh);
    echo '</urlset>' . "\n";
}

// ─── Main ─────────────────────────────────────────────────────────────────────
if (!is_readable(KW_FILE)) {
    header('HTTP/1.1 500 Internal Server Error');
    ob_end_clean();
    exit('keyword1.txt tidak ditemukan');
}

$baseUrl = rtrim(BASE_URL, '/');
$total   = countKwLines();
ob_clean();

if (isset($_GET['page'])) {
    outputPage((int)$_GET['page'], $total, $baseUrl);
} else {
    outputIndex($total, $baseUrl);
}

ob_end_flush();
exit;