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

// 2. SET HEADERS
// This tells the browser/search engine that this is an XML file, not HTML
header("Content-Type: application/xml; charset=utf-8");

// 3. OUTPUT XML DECLARATION
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

// --- SETTINGS ---
// Ensure base URL doesn't have a trailing slash for consistency
$base_url = rtrim($siteurlnav, '/'); 
$category_pattern = '/ringtone/'; // Matches your $sitecategorypatternurl

// --- 4. ADD HOMEPAGE (Static) ---
echo '  <url>' . PHP_EOL;
echo '    <loc>' . htmlspecialchars($base_url . '/') . '</loc>' . PHP_EOL;
echo '    <changefreq>daily</changefreq>' . PHP_EOL;
echo '    <priority>1.0</priority>' . PHP_EOL;
echo '  </url>' . PHP_EOL;

// --- 5. FETCH POSTS FROM DATABASE ---
// We select URLSLIST to build the link and modified_date for SEO freshness
// Note: We do NOT use LIMIT here because a sitemap should contain all links.
$sql = "SELECT URLSLIST, modified_date FROM $tablename ORDER BY modified_date DESC";
$result = $con->query($sql);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        
        // Logic from your index page to generate the slug
        $fullUrl = $row["URLSLIST"];
        $slug = basename($fullUrl);
        
        // Construct the full absolute URL
        $loc_url = $base_url . $category_pattern . $slug;
        
        // Format Date to ISO 8601 (Required by Google)
        // If modified_date is empty, default to today, otherwise parse DB date
        $db_date = $row['modified_date'];
        if (!empty($db_date) && $db_date != '0000-00-00 00:00:00') {
            $last_mod = date('c', strtotime($db_date));
        } else {
            $last_mod = date('c'); // Current time as fallback
        }

        // Output the XML block for this song
        echo '  <url>' . PHP_EOL;
        echo '    <loc>' . htmlspecialchars($loc_url) . '</loc>' . PHP_EOL;
        echo '    <lastmod>' . $last_mod . '</lastmod>' . PHP_EOL;
        echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
        echo '    <priority>0.8</priority>' . PHP_EOL;
        echo '  </url>' . PHP_EOL;
    }
}

// 6. CLOSE XML TAGS & CONNECTION
echo '</urlset>';

if (isset($con)) {
    $con->close();
}
?>