<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$hust_file = __DIR__ . '/hust.txt';
if (!file_exists($hust_file)) die("File hust.txt tidak ditemukan!");
$hust_content = file_get_contents($hust_file);
if ($hust_content === false) die("Gagal membaca hust.txt");

$hust_lines = array_values(array_filter(array_map('trim', explode("\n", $hust_content))));
$total_lines = count($hust_lines);
if ($total_lines === 0) die("File hust.txt kosong!");

$sitemap_count = 4;
$per_sitemap = ceil($total_lines / $sitemap_count);

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

function formatXML($xml_string) {
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($xml_string);
    return $dom->saveXML();
}

for ($i = 0; $i < $sitemap_count; $i++) {
    $start = $i * $per_sitemap + 1;
    $end = min(($i + 1) * $per_sitemap, $total_lines);
    $sitemap_filename = __DIR__ . "/sitemap" . ($i + 1) . ".xml";

    $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset></urlset>');
    $xml->addAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

    for ($j = $start; $j <= $end; $j++) {
        $url = $xml->addChild('url');
        $link = $base_url . "/?resmi_2026=" . $j;
        $url->addChild('loc', htmlspecialchars($link, ENT_QUOTES, 'UTF-8'));
        $url->addChild('lastmod', date('Y-m-d'));
        $url->addChild('changefreq', 'daily');
        $url->addChild('priority', '0.8');
    }

    $formatted_xml = formatXML($xml->asXML());
    file_put_contents($sitemap_filename, $formatted_xml);

    echo "✅ Sitemap " . ($i + 1) . " berhasil dibuat: $sitemap_filename<br>";
}

$robots_file = __DIR__ . "/robots.txt";
$robots_content = "User-agent: *\nAllow: /\n\n";
for ($i = 1; $i <= $sitemap_count; $i++) {
    $robots_content .= "Sitemap: {$base_url}/sitemap{$i}.xml\n";
}
file_put_contents($robots_file, $robots_content);

echo "<br>✅ robots.txt berhasil dibuat: $robots_file<br>";
echo "<br>🎉 Semua sitemap & robots.txt selesai dibuat dengan rapi!<br>";
?>