<?php
// ============================================================
// sitemap.php
// Dynamically generates a Google-compliant XML Sitemap
// Reads structural parameters directly from posts.json
// ============================================================

// Set correct header context so browsers and crawlers treat it as XML
header("Content-Type: application/xml; charset=utf-8");

$baseUrl   = 'https://www.ringdoorbellsetup.tech';
$postsFile = __DIR__ . '/posts.json';

// Define your static, permanent structural pages
$staticPages = [
    '', // Homepage
    '/about_us.html',
    '/faq.html',
    '/blog.php',
    '/contact.html',
    '/privacy-policy.html',
    '/termconditons.html'
];

// Initialize XML data output string
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

// 1. Output Static Landing Pages
foreach ($staticPages as $page) {
    // Give core index landing spots slightly higher prioritization weight
    $priority = ($page === '' || $page === '/blog.php') ? '1.0' : '0.8';
    
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . $baseUrl . $page . '</loc>' . PHP_EOL;
    echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
    echo '    <priority>' . $priority . '</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
}

// 2. Output Dynamic Blog Posts from JSON
if (file_exists($postsFile)) {
    $data = file_get_contents($postsFile);
    $allPosts = json_decode($data, true) ?: [];
    
    foreach ($allPosts as $post) {
        // Only index posts that are actively marked as published
        if (($post['status'] ?? '') === 'published' && !empty($post['slug'])) {
            $cleanUrl = $baseUrl . '/' . urlencode($post['slug']);
            
            // Format dates cleanly. Fallback to current year stamp if missing
            $rawDate = $post['updated'] ?? $post['date'] ?? '2026-03-15';
            $formattedDate = date('Y-m-d', strtotime($rawDate));

            echo '  <url>' . PHP_EOL;
            echo '    <loc>' . htmlspecialchars($cleanUrl) . '</loc>' . PHP_EOL;
            echo '    <lastmod>' . $formattedDate . '</lastmod>' . PHP_EOL;
            echo '    <changefreq>monthly</changefreq>' . PHP_EOL;
            echo '    <priority>0.6</priority>' . PHP_EOL;
            echo '  </url>' . PHP_EOL;
        }
    }
}

echo '</urlset>';