<?php
// Start buffering immediately to catch any stray output from includes
ob_start();

error_reporting(0);
ini_set('display_errors', 0);

// Helper: XML-safe URL
function xmlUrl($url) {
    return htmlspecialchars(trim($url), ENT_XML1, 'UTF-8');
}

// Helper: Safe date
function xmlDate($dateStr) {
    if (empty($dateStr)) return date('Y-m-d');
    $ts = strtotime($dateStr);
    return $ts ? date('Y-m-d', $ts) : date('Y-m-d');
}

// Load DB — any stray output from db.php gets caught by ob_start()
require "system/db.php";

// Discard ANY stray output from db.php (whitespace, BOM, errors, etc.)
ob_end_clean();

// Now send clean headers and XML
header("Content-Type: application/xml; charset=utf-8");

$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

/* ===================== */
/* STATIC URLS           */
/* ===================== */
$staticUrls = [
    "https://genixfertilitycare.com/",
    "https://genixfertilitycare.com/about/",
    "https://genixfertilitycare.com/contact/",
    "https://genixfertilitycare.com/facilities/",
    "https://genixfertilitycare.com/ivf-2/",
    "https://genixfertilitycare.com/iui-2/",
    "https://genixfertilitycare.com/icsi-2/",
    "https://genixfertilitycare.com/imsi-2/",
    "https://genixfertilitycare.com/vitrification-5/",
    "https://genixfertilitycare.com/gynecologist-in-bhubaneswar/",
    "https://genixfertilitycare.com/image-gallery/",
    "https://genixfertilitycare.com/video-gallery/",
    "https://genixfertilitycare.com/appointment/",
    "https://genixfertilitycare.com/privacy-policy/",
    "https://genixfertilitycare.com/terms-condition/",
    "https://genixfertilitycare.com/blog/",
];

foreach ($staticUrls as $url) {
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . xmlUrl($url) . "</loc>\n";
    $xml .= "    <changefreq>monthly</changefreq>\n";
    $xml .= "    <priority>0.8</priority>\n";
    $xml .= "  </url>\n";
}

/* ===================== */
/* DYNAMIC BLOG URLS     */
/* ===================== */
try {
    $stmt = $conn->query("SELECT url, updated_at FROM blog WHERE status = 1 ORDER BY updated_at DESC");

    if ($stmt) {
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            if (empty($row['url'])) continue;

            $slug    = rawurlencode(trim($row['url']));
            $blogUrl = "https://genixfertilitycare.com/blog/" . $slug;
            $lastmod = xmlDate($row['updated_at']);

            $xml .= "  <url>\n";
            $xml .= "    <loc>" . xmlUrl($blogUrl) . "</loc>\n";
            $xml .= "    <lastmod>" . $lastmod . "</lastmod>\n";
            $xml .= "    <changefreq>weekly</changefreq>\n";
            $xml .= "    <priority>0.6</priority>\n";
            $xml .= "  </url>\n";
        }
    }
} catch (Exception $e) {
    // Fail silently
}

$xml .= '</urlset>';

// Output the fully built XML string — guaranteed clean
echo $xml;
exit;