<?php
// 1. Set the correct header for XML
header("Content-Type: application/xml; charset=utf-8");

// 2. Hide errors so they don't break the XML formatting
ini_set('display_errors', 0);

// 3. Connect to your database
require_once __DIR__ . '/db_connect.php';

// 4. Start the XML output
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org">

  <!-- Static Pages -->
  <url>
    <loc>https://fieldsrealty.co.za</loc>
    <changefreq>daily</changefreq>
    <priority>1.0</priority>
  </url>

  <?php
  try {
      // 5. Fetch all active listings to create dynamic URLs
      $stmt = $conn->prepare("SELECT id, updated_at FROM listings WHERE status='Active' ORDER BY id DESC");
      $stmt->execute();
      $listings = $stmt->fetchAll(PDO::FETCH_ASSOC);

      foreach ($listings as $row) {
          // Adjust the URL structure below to match how your property pages are actually accessed
          echo '<url>';
          echo '<loc>https://fieldsrealty.co.zaproperty-details.php?id=' . $row['id'] . '</loc>';
          echo '<lastmod>' . date('Y-m-d', strtotime($row['updated_at'] ?? 'now')) . '</lastmod>';
          echo '<changefreq>weekly</changefreq>';
          echo '<priority>0.8</priority>';
          echo '</url>';
      }
  } catch (Exception $e) {
      // Silently fail if DB is down so XML doesn't break
  }
  ?>

</urlset>
