<?php 
require('includes/cmain.inc.php'); 

// Ensure no output is sent before XML declaration
ob_start();

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

// XML declaration
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL; 
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
               xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
               http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . PHP_EOL;

global $conn; // Ensure $conn is defined

$query = "SELECT tc.country_name, tc.country_url, tc.updated_on, 
                 ts.state_name, tcy.county_name 
          FROM tbl_country tc 
          JOIN tbl_county tcy ON tc.country_status = tcy.country_id 
          JOIN tbl_state ts ON tcy.state_id = ts.state_id 
          WHERE tc.parent_childs != '0' 
          ORDER BY ts.state_name ASC 
          LIMIT 0, 49000";

$result =db_query($query);

if (!$result) {
    die("<!-- Database Query Failed: " . mysqli_error($conn) . " -->");
}

while ($row = mysqli_fetch_assoc($result)) {
    $link2 = strtolower(str_replace(" ", "-", trim($row['country_url'])));
    $link3 = strtolower(str_replace(" ", "-", trim($row['state_name'])));
    $link4 = strtolower(str_replace(" ", "-", trim($row['county_name'])));
    $testurl = SITE_WS_PATH . "/" . $link2 . "/" . $link3 . "/" . $link4;

    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . htmlspecialchars($testurl) . '</loc>' . PHP_EOL;

    // Ensure date format follows W3C guidelines
    $w3cDatetime = gmdate('Y-m-d\TH:i:s\Z', strtotime($row["updated_on"]));
    echo '    <lastmod>' . $w3cDatetime . '</lastmod>' . PHP_EOL;

    echo '    <priority>0.80</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
}

echo '</urlset>' . PHP_EOL;

// Ensure no unwanted output
ob_end_flush();
?>
