<?php
// 1. CONFIGURATION
include('databaseconnect.php');
include('sitedetails.php');

// Increase memory limit for processing large arrays of tags
ini_set('memory_limit', '256M');

// Helper function to format URLs (matches your main script logic)
function urlformat_xml($string) {
    $string = strtolower($string);
    $string = str_replace([' ', '_'], '-', $string);
    $string = preg_replace('/[^a-z0-9\-]/', '', $string);
    $string = preg_replace('/-+/', '-', $string);
    return trim($string, '-');
}

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

$limit = 1000; // URLs per XML file
$base_url = rtrim($siteurlnav, '/');
$url_prefix = '/category/';

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

// 2. DATA COLLECTION
// We fetch only the relevant columns to save memory
$sql = "SELECT album, tags, year, musicdirectors, stars, song_mood_tags FROM $tablename";
$result = $con->query($sql);

$raw_terms = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        
        // A. Simple Columns (Single values)
        // ---------------------------------
        
        // 1. Album
        if (!empty($row['album'])) {
            $raw_terms[] = $row['album'];
        }
        
        // 2. Year (Convert int to string)
        if (!empty($row['year']) && $row['year'] != 0) {
            $raw_terms[] = (string)$row['year'];
        }

        // B. Comma Separated Columns (Multiple values)
        // --------------------------------------------
        
        // Helper to merge arrays quickly
        $multi_columns = [
            $row['tags'], 
            $row['musicdirectors'], 
            $row['stars'], 
            $row['song_mood_tags']
        ];

        foreach ($multi_columns as $col_data) {
            if (!empty($col_data)) {
                // Explode by comma
                $items = explode(',', $col_data);
                foreach ($items as $item) {
                    $trimmed = trim($item);
                    if ($trimmed !== '') {
                        $raw_terms[] = $trimmed;
                    }
                }
            }
        }
    }
}

// 3. PROCESS & UNIQUE
// Clean formatting and remove duplicates
$unique_urls = [];

// Use array_flip to handle uniqueness faster than array_unique for large strings
$temp_map = [];

foreach ($raw_terms as $term) {
    $slug = urlformat_xml($term);
    if (!empty($slug)) {
        // We use the slug as the key to ensure uniqueness
        // Example: "2023" and " 2023 " become the same key
        $temp_map[$slug] = true;
    }
}

// Convert keys back to URL paths
foreach (array_keys($temp_map) as $slug) {
    $unique_urls[] = $url_prefix . $slug;
}

// Clean up memory
unset($raw_terms);
unset($temp_map);

// 4. CALCULATE PAGINATION
$total_records = count($unique_urls);
$total_pages = ceil($total_records / $limit);
if ($total_pages == 0) $total_pages = 1;

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

// --- MODE A: SHOW INDEX (sitemap_category.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;
        // Links to sitemap_category1.xml, sitemap_category2.xml
        echo '    <loc>' . $base_url . '/sitemap_category' . $i . '.xml</loc>' . PHP_EOL;
        echo '    <lastmod>' . date('c') . '</lastmod>' . PHP_EOL;
        echo '  </sitemap>' . PHP_EOL;
    }
    echo '</sitemapindex>';
}

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

    // Slice array for current page
    $start_offset = ($page - 1) * $limit;
    $chunk = array_slice($unique_urls, $start_offset, $limit);

    foreach ($chunk as $path) {
        echo '  <url>' . PHP_EOL;
        echo '    <loc>' . htmlspecialchars($base_url . $path) . '</loc>' . PHP_EOL;
        echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
        echo '    <priority>0.6</priority>' . PHP_EOL;
        echo '  </url>' . PHP_EOL;
    }
    echo '</urlset>';
}

$con->close();
?>