<?php
include('databaseconnect.php');
include('sitedetails.php');

header("Content-Type: application/xml; charset=utf-8");

$limit = 1000;
$base_url = rtrim($siteurlnav, '/');
$pattern = '/ringtone/';

// Check Input
$mode = isset($_GET['mode']) ? $_GET['mode'] : 'posts';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;

// 1. Calculate Total Records
$sql_count = "SELECT COUNT(ID) AS total FROM $tablename";
$result_count = $con->query($sql_count);
$row_count = $result_count->fetch_assoc();
$total_records = $row_count['total'];
$total_pages = ceil($total_records / $limit);

echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;

// --- MODE A: SHOW INDEX (sitemap_ringtones.xml) ---
if ($mode == 'index') {
    echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
    
    for ($i = 1; $i <= $total_pages; $i++) {
        echo '  <sitemap>' . PHP_EOL;
        // This links to sitemap1.xml, sitemap2.xml, etc.
        echo '    <loc>' . $base_url . '/sitemap' . $i . '.xml</loc>' . PHP_EOL;
        echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
        echo '  </sitemap>' . PHP_EOL;
    }
    echo '</sitemapindex>';
} 

// --- MODE B: SHOW URLS (sitemap1.xml, etc.) ---
else {
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

    $start_from = ($page - 1) * $limit;
    
    $sql = "SELECT URLSLIST, modified_date FROM $tablename ORDER BY modified_date DESC LIMIT $start_from, $limit";
    $result = $con->query($sql);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $slug = basename($row["URLSLIST"]);
            $full_link = $base_url . $pattern . $slug;
            
            $date = $row['modified_date'];
            $mod_time = (!empty($date) && $date != '0000-00-00 00:00:00') ? date('c', strtotime($date)) : date('c');

            echo '  <url>' . PHP_EOL;
            echo '    <loc>' . htmlspecialchars($full_link) . '</loc>' . PHP_EOL;
            echo '    <lastmod>' . $mod_time . '</lastmod>' . PHP_EOL;
            echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
            echo '  </url>' . PHP_EOL;
        }
    }
    echo '</urlset>';
}
$con->close();
?>