<?php
// sitemap.php
require_once 'db_connect.php';

// Set correct header for XML output
header("Content-Type: application/xml; charset=utf-8");

$base_url = "https://locateaserver.com/";

// Begin XML structure
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// 1. Output the primary Homepage URL
echo "  <url>\n";
echo "    <loc>" . htmlspecialchars($base_url) . "</loc>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>1.0</priority>\n";
echo "  </url>\n";

// 2. Query the database for active states
try {
    $sql = "SELECT DISTINCT UPPER(state) as state FROM process_servers WHERE status = 'active' AND state IS NOT NULL AND state != ''";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $states = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Loop through results and generate a URL node for each state
    foreach ($states as $row) {
        $stateCode = trim($row['state']);
        
        // Ensure strictly 2-letter state codes to prevent malformed URLs
        if (preg_match('/^[A-Z]{2}$/', $stateCode)) {
            $state_url = $base_url . "?state=" . $stateCode;
            
            echo "  <url>\n";
            echo "    <loc>" . htmlspecialchars($state_url) . "</loc>\n";
            echo "    <changefreq>weekly</changefreq>\n";
            echo "    <priority>0.8</priority>\n";
            echo "  </url>\n";
        }
    }
} catch (PDOException $e) {
    // Fail silently in the XML output to prevent breaking the schema format for search engines
}

// Close XML structure
echo '</urlset>';
?>