<?php
// Path to your JSON file containing posts
$jsonFile = __DIR__ . '/admin/posts.json';

// Read and decode JSON
if (!file_exists($jsonFile)) {
    die('JSON file not found.');
}

$jsonData = file_get_contents($jsonFile);
$posts = json_decode($jsonData, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    die('Invalid JSON format.');
}

// Base URL of your site
$baseUrl = 'https://cryptobitsense.com';

// Create XML structure
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset></urlset>');
$xml->addAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

// Loop through posts and add to sitemap
foreach ($posts as $post) {
    // Assuming your JSON structure has keys like: id, slug, date
    $id = isset($post['id']) ? $post['id'] : '';
    $lastmod = isset($post['published_at']) ? date('Y-m-d', strtotime($post['published_at'])) : date('Y-m-d');

    if (!empty($id)) {
        $url = $xml->addChild('url');
        $url->addChild('loc', htmlspecialchars($baseUrl . 'postDetail?id=' . $id, ENT_QUOTES, 'UTF-8'));
        $url->addChild('lastmod', $lastmod);
        $url->addChild('changefreq', 'weekly');
        $url->addChild('priority', '0.8');
    }
}

// Output XML
header('Content-Type: application/xml');
echo $xml->asXML();
