// ── WRITE SITEMAP INDEX + per-category sitemaps ────────────
// One sitemap per category = Google crawls each category's new
// pages more efficiently. The index file points to all of them.

$sitemapIndexFile = $baseDir . '/sitemap-index.xml';
$categorySitemaps = []; // track which files we write

// Group calculators by category
$byCategory = [];
foreach ($calculators as $calc) {
    $byCategory[$calc['cat']][] = $calc;
}

foreach ($byCategory as $cat => $calcs) {
    $catSitemapFile = $baseDir . '/sitemap-' . $cat . '.xml';
    $catXml = new DOMDocument('1.0', 'UTF-8');
    $catXml->formatOutput = true;
    $catUrlset = $catXml->createElement('urlset');
    $catUrlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

    foreach ($calcs as $calc) {
        $u = $catXml->createElement('url');
        $u->appendChild($catXml->createElement('loc', 'https://calculatorcove.com' . $calc['url']));
        $u->appendChild($catXml->createElement('lastmod', date('c')));
        $u->appendChild($catXml->createElement('changefreq', 'monthly'));
        $u->appendChild($catXml->createElement('priority', '0.8'));
        $catUrlset->appendChild($u);
    }
    $catXml->appendChild($catUrlset);
    $catXml->save($catSitemapFile);
    $categorySitemaps[] = [
        'file' => 'sitemap-' . $cat . '.xml',
        'count' => count($calcs),
    ];
    logLine("Wrote sitemap-$cat.xml — " . count($calcs) . " URLs");
}

// Write sitemap index
$idxXml = new DOMDocument('1.0', 'UTF-8');
$idxXml->formatOutput = true;
$idxRoot = $idxXml->createElement('sitemapindex');
$idxRoot->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

// Main sitemap
$sm = $idxXml->createElement('sitemap');
$sm->appendChild($idxXml->createElement('loc', 'https://calculatorcove.com/sitemap.xml'));
$sm->appendChild($idxXml->createElement('lastmod', date('c')));
$idxRoot->appendChild($sm);

// Category sitemaps
foreach ($categorySitemaps as $cs) {
    $sm = $idxXml->createElement('sitemap');
    $sm->appendChild($idxXml->createElement('loc', 'https://calculatorcove.com/' . $cs['file']));
    $sm->appendChild($idxXml->createElement('lastmod', date('c')));
    $idxRoot->appendChild($sm);
}

$idxXml->appendChild($idxRoot);
$idxXml->save($sitemapIndexFile);
logLine("sitemap-index.xml written — " . (1 + count($categorySitemaps)) . " sitemaps");