<?php
/**
 * TCC Custom Sitemap Index
 * Upload to: /public_html/sitemap_index.php
 */
define( 'SHORTINIT', false );

// Load WordPress silently - suppress any output
ob_start();
require_once( dirname( __FILE__ ) . '/wp-load.php' );
ob_end_clean();

// Kill any further output buffering from plugins/theme
while ( ob_get_level() > 0 ) {
    ob_end_clean();
}

global $wpdb;

$base  = 'https://truecouchcleaning.com.au/';
$today = gmdate( 'Y-m-d\TH:i:s+00:00' );

$states = [ 'act', 'nsw', 'qld', 'vic', 'sa', 'wa', 'nt', 'tas' ];

$post_mod = $wpdb->get_var( "SELECT MAX(post_modified_gmt) FROM {$wpdb->posts} WHERE post_status='publish' AND post_type='post'" );
$page_mod = $wpdb->get_var( "SELECT MAX(post_modified_gmt) FROM {$wpdb->posts} WHERE post_status='publish' AND post_type='page'" );

$post_lastmod = $post_mod ? gmdate( 'Y-m-d\TH:i:s+00:00', strtotime( $post_mod ) ) : $today;
$page_lastmod = $page_mod ? gmdate( 'Y-m-d\TH:i:s+00:00', strtotime( $page_mod ) ) : $today;

// Send headers
header( 'Content-Type: application/xml; charset=UTF-8' );
header( 'X-Robots-Tag: noindex, follow' );
header( 'Cache-Control: no-cache, no-store, must-revalidate' );

// Output clean XML — NO whitespace before <?xml
$out  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$out .= '<?xml-stylesheet type="text/xsl" href="//truecouchcleaning.com.au/main-sitemap.xsl"?>' . "\n";
$out .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// Posts
$out .= "\t<sitemap>\n";
$out .= "\t\t<loc>" . $base . "tcc-posts-sitemap.xml</loc>\n";
$out .= "\t\t<lastmod>" . $post_lastmod . "</lastmod>\n";
$out .= "\t</sitemap>\n";

// Pages
$out .= "\t<sitemap>\n";
$out .= "\t\t<loc>" . $base . "tcc-pages-sitemap.xml</loc>\n";
$out .= "\t\t<lastmod>" . $page_lastmod . "</lastmod>\n";
$out .= "\t</sitemap>\n";

// States
foreach ( $states as $state ) {
    $mod = $wpdb->get_var( $wpdb->prepare(
        "SELECT MAX(post_modified_gmt) FROM {$wpdb->posts}
         WHERE post_status='publish'
           AND post_type IN ('page','post')
           AND guid LIKE %s",
        '%/' . $state . '/%'
    ) );
    $lastmod = $mod ? gmdate( 'Y-m-d\TH:i:s+00:00', strtotime( $mod ) ) : $today;

    $out .= "\t<sitemap>\n";
    $out .= "\t\t<loc>" . $base . "tcc-sitemap-" . $state . ".xml</loc>\n";
    $out .= "\t\t<lastmod>" . $lastmod . "</lastmod>\n";
    $out .= "\t</sitemap>\n";
}

$out .= '</sitemapindex>';

echo $out;
exit;