<?php
define('WP_USE_THEMES', false);
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');

while (ob_get_level()) ob_end_clean();

header("Content-Type: application/xml; charset=utf-8");

global $wpdb;

$limit = 50000;

// تعداد کل نوشته‌های منتشر شده
$total = $wpdb->get_var("
    SELECT COUNT(ID)
    FROM {$wpdb->posts}
    WHERE post_status = 'publish'
    AND post_type = 'post'
");

$total_parts = ceil($total / $limit);

// اگر پارامتر part وجود نداشت → sitemap index بساز
if (!isset($_GET['part'])) {

    echo '<?xml version="1.0" encoding="UTF-8"?>';
    echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

    for ($i = 1; $i <= $total_parts; $i++) {
        echo '<sitemap>';
        echo '<loc>'.home_url('/sitemap-'.$i.'.xml').'</loc>';
        echo '<lastmod>'.date('c').'</lastmod>';
        echo '</sitemap>';
    }

    echo '</sitemapindex>';
    exit;
}

// ساخت هر بخش
$part = (int) $_GET['part'];
$offset = ($part - 1) * $limit;

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

$posts = $wpdb->get_results(
    $wpdb->prepare("
        SELECT ID, post_modified
        FROM {$wpdb->posts}
        WHERE post_status = 'publish'
        AND post_type = 'post'
        ORDER BY ID ASC
        LIMIT %d OFFSET %d
    ", $limit, $offset)
);

foreach ($posts as $post) {
    echo '<url>';
    echo '<loc>'.get_permalink($post->ID).'</loc>';
    echo '<lastmod>'.date('c', strtotime($post->post_modified)).'</lastmod>';
    echo '</url>';
}

echo '</urlset>';
exit;