<?php
/**
 * Sitemap Backlink Generator (single file)
 * - Paste daftar URL -> auto jadi sitemap-backlink-1.xml, 2, 3, ... + sitemap-index.xml
 * - Batasi 50.000 URL per file (standar Google)
 * - Opsi lastmod (YYYY-MM-DD), prefix nama file, dan Base Public URL (untuk <loc> di sitemap-index)
 * - Hasil dijadikan ZIP untuk diunduh
 * 
 * Simpan sebagai: sitemap_maker.php, upload ke hosting, akses via browser.
 */
ini_set('display_errors', 0);
error_reporting(E_ALL);

const MAX_URLS_PER_SITEMAP = 50000;

function isValidUrl($url) {
    if (!preg_match('~^https?://~i', $url)) return false;
    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

function buildSitemapXml(array $urls, ?string $lastmod = null) {
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->formatOutput = true;

    $urlset = $dom->createElement('urlset');
    $xmlns = $dom->createAttribute('xmlns');
    $xmlns->value = 'http://www.sitemaps.org/schemas/sitemap/0.9';
    $urlset->appendChild($xmlns);
    $dom->appendChild($urlset);

    foreach ($urls as $u) {
        $url = $dom->createElement('url');
        $loc = $dom->createElement('loc', htmlspecialchars($u, ENT_XML1|ENT_COMPAT, 'UTF-8'));
        $url->appendChild($loc);

        if ($lastmod) {
            // Validasi sederhana format YYYY-MM-DD
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $lastmod)) {
                $url->appendChild($dom->createElement('lastmod', $lastmod));
            }
        }

        $urlset->appendChild($url);
    }
    return $dom->saveXML();
}

function buildSitemapIndexXml(array $fileNames, ?string $basePublicUrl = null) {
    $today = (new DateTime('now'))->format('Y-m-d');

    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->formatOutput = true;

    $sitemapindex = $dom->createElement('sitemapindex');
    $xmlns = $dom->createAttribute('xmlns');
    $xmlns->value = 'http://www.sitemaps.org/schemas/sitemap/0.9';
    $sitemapindex->appendChild($xmlns);
    $dom->appendChild($sitemapindex);

    foreach ($fileNames as $fn) {
        $sm = $dom->createElement('sitemap');

        $locValue = $fn;
        if ($basePublicUrl) {
            // Pastikan basePublicUrl berakhiran "/" tepat satu
            $base = rtrim($basePublicUrl, '/') . '/';
            $locValue = $base . ltrim($fn, '/');
        }

        $loc = $dom->createElement('loc', htmlspecialchars($locValue, ENT_XML1|ENT_COMPAT, 'UTF-8'));
        $sm->appendChild($loc);

        $lastmod = $dom->createElement('lastmod', $today);
        $sm->appendChild($lastmod);

        $sitemapindex->appendChild($sm);
    }

    return $dom->saveXML();
}

function createZipFromFiles(array $filesMap, $zipPath) {
    $zip = new ZipArchive();
    if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
        throw new RuntimeException('Gagal membuat ZIP.');
    }
    foreach ($filesMap as $name => $content) {
        $zip->addFromString($name, $content);
    }
    $zip->close();
}

function sanitizePrefix($s) {
    $s = trim($s);
    if ($s === '') return 'sitemap-backlink';
    // hanya huruf, angka, dash, underscore, titik
    $s = preg_replace('/[^a-zA-Z0-9\-\_\.]/', '-', $s);
    return $s;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw = $_POST['urls'] ?? '';
    $lastmod = trim($_POST['lastmod'] ?? '');
    $prefix = sanitizePrefix($_POST['prefix'] ?? 'sitemap-backlink');
    $basePublicUrl = trim($_POST['base_url'] ?? '');

    // Ambil URL baris per baris
    $lines = preg_split('/\R+/', $raw);
    $urls = [];
    foreach ($lines as $line) {
        $u = trim($line);
        if ($u === '') continue;
        if (isValidUrl($u)) $urls[] = $u;
    }

    // Hapus duplikat, pertahankan urutan
    $urls = array_values(array_unique($urls));

    if (empty($urls)) {
        $error = 'Tidak ada URL valid yang ditemukan. Pastikan format http(s)://...';
    } else {
        // Pecah menjadi chunk 50k
        $chunks = array_chunk($urls, MAX_URLS_PER_SITEMAP);
        $filesMap = [];
        $names = [];
        $i = 1;
        foreach ($chunks as $chunk) {
            $name = $prefix . '-' . $i . '.xml';
            $xml = buildSitemapXml($chunk, $lastmod ?: null);
            $filesMap[$name] = $xml;
            $names[] = $name;
            $i++;
        }

        // Buat sitemap-index.xml
        $indexXml = buildSitemapIndexXml($names, $basePublicUrl ?: null);
        $filesMap['sitemap-index.xml'] = $indexXml;

        // Buat ZIP untuk diunduh
        $tmpDir = sys_get_temp_dir();
        $zipName = 'sitemaps-' . date('Ymd-His') . '.zip';
        $zipPath = $tmpDir . DIRECTORY_SEPARATOR . $zipName;

        try {
            createZipFromFiles($filesMap, $zipPath);

            // Kirim file ZIP ke browser
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="'.$zipName.'"');
            header('Content-Length: ' . filesize($zipPath));
            readfile($zipPath);
            @unlink($zipPath);
            exit;
        } catch (Throwable $e) {
            $error = 'Gagal membuat ZIP: ' . $e->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="id">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Sitemap Backlink Generator</title>
<style>
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;background:#0b1220;color:#e6e6e6;margin:0;padding:24px}
.container{max-width:980px;margin:0 auto}
.card{background:#111827;border:1px solid #22304a;border-radius:16px;padding:20px;box-shadow:0 10px 30px rgba(0,0,0,.35)}
h1{margin:0 0 16px;font-size:24px}
label{display:block;margin:12px 0 6px;color:#cbd5e1}
textarea,input{width:100%;box-sizing:border-box;border-radius:12px;border:1px solid #334155;background:#0f172a;color:#e2e8f0;padding:12px}
.small{font-size:12px;color:#94a3b8}
.row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
button{background:#22c55e;border:none;color:#052e13;padding:12px 16px;border-radius:12px;font-weight:700;cursor:pointer;margin-top:12px}
button:hover{filter:brightness(1.05)}
.error{background:#7f1d1d;border:1px solid #b91c1c;padding:10px;border-radius:12px;margin-bottom:12px}
.help{margin-top:16px;font-size:13px;color:#a5b4fc}
code{background:#0b1220;border:1px solid #22304a;padding:2px 6px;border-radius:8px}
</style>
</head>
<body>
<div class="container">
  <div class="card">
    <h1>🗺️ Sitemap Backlink Generator</h1>
    <p class="small">Tempel daftar URL backlink (satu per baris). Script ini akan membuat <code>sitemap-index.xml</code> + <code><?= htmlspecialchars(sanitizePrefix($_POST['prefix'] ?? 'sitemap-backlink')) ?>-1.xml</code>, <code>-2.xml</code>, dst (maks. 50.000 URL per file) dan memberikan file ZIP untuk diunduh.</p>
    <?php if(!empty($error)): ?>
      <div class="error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <form method="post">
      <label for="urls">Daftar URL (satu per baris)</label>
      <textarea id="urls" name="urls" rows="12" placeholder="https://contoh-domain1.com/post-abc
https://contoh-domain2.org/artikel-xyz
https://contoh-domain3.net/index.html"><?= isset($_POST['urls']) ? htmlspecialchars($_POST['urls']) : '' ?></textarea>

      <div class="row">
        <div>
          <label for="lastmod">lastmod (opsional, format YYYY-MM-DD)</label>
          <input id="lastmod" name="lastmod" type="text" placeholder="<?= date('Y-m-d') ?>" value="<?= isset($_POST['lastmod']) ? htmlspecialchars($_POST['lastmod']) : '' ?>">
          <div class="small">Jika diisi, semua URL akan memakai tanggal ini sebagai <code>&lt;lastmod&gt;</code>.</div>
        </div>
        <div>
          <label for="prefix">Prefix nama file sitemap</label>
          <input id="prefix" name="prefix" type="text" placeholder="sitemap-backlink" value="<?= isset($_POST['prefix']) ? htmlspecialchars($_POST['prefix']) : 'sitemap-backlink' ?>">
          <div class="small">Contoh hasil: <code>prefix-1.xml</code>, <code>prefix-2.xml</code>, …</div>
        </div>
      </div>

      <label for="base_url">Base Public URL (opsional, untuk &lt;loc&gt; di sitemap-index)</label>
      <input id="base_url" name="base_url" type="url" placeholder="https://pub-xxxxx.r2.dev" value="<?= isset($_POST['base_url']) ? htmlspecialchars($_POST['base_url']) : '' ?>">
      <div class="small">Jika diisi, <code>&lt;loc&gt;</code> di <code>sitemap-index.xml</code> akan berbentuk <code>https://pub-xxxxx.r2.dev/prefix-1.xml</code>. Jika kosong, hanya nama file (bisa kamu edit nanti).</div>

      <button type="submit">Generate & Download ZIP</button>
    </form>

    <div class="help">
      <p><strong>Cara pakai cepat:</strong></p>
      <ol>
        <li>Tempel semua URL backlink kamu.</li>
        <li>(Opsional) isi <em>lastmod</em> dan <em>Base Public URL</em> R2 kamu (misal: <code>https://pub-6b20634c67004935b3cc53e8cc5132c1.r2.dev</code>).</li>
        <li>Klik <strong>Generate</strong> → unduh ZIP.</li>
        <li>Upload isi ZIP ke bucket R2 (set Public).</li>
        <li>Submit <code>sitemap-index.xml</code> ke Google Search Console.</li>
      </ol>
    </div>
  </div>
</div>
</body>
</html>
