<?php

declare(strict_types=1);

header('Content-Type: application/xml; charset=utf-8');

$siteBase = 'https://kingsforge.co.ke';
$cmsBase = 'https://cms.kingsforge.co.ke';

function kf_sitemap_fetch_json(string $url): array
{
    $context = stream_context_create([
        'http' => [
            'timeout' => 8,
            'ignore_errors' => true,
            'header' => "Accept: application/json\r\n",
        ],
    ]);

    $raw = @file_get_contents($url, false, $context);
    if (!is_string($raw) || trim($raw) === '') {
        return [];
    }

    $decoded = json_decode($raw, true);
    return is_array($decoded) ? $decoded : [];
}

function kf_sitemap_xml_escape(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_XML1, 'UTF-8');
}

$today = gmdate('Y-m-d');
$entries = [
    ['loc' => $siteBase . '/', 'lastmod' => $today],
    ['loc' => $siteBase . '/case-studies', 'lastmod' => $today],
    ['loc' => $siteBase . '/blog', 'lastmod' => $today],
];

$caseStudies = kf_sitemap_fetch_json($cmsBase . '/api/case-studies.php');
if (is_array($caseStudies)) {
    foreach ($caseStudies as $item) {
        $slug = trim((string) ($item['slug'] ?? ''));
        if ($slug === '') {
            continue;
        }

        $entries[] = [
            'loc' => $siteBase . '/case-study/' . rawurlencode($slug),
            'lastmod' => $today,
        ];
    }
}

$page = 1;
$totalPages = 1;
while ($page <= $totalPages) {
    $blogPayload = kf_sitemap_fetch_json($cmsBase . '/api/blog.php?page=' . $page . '&per_page=100');
    $items = is_array($blogPayload['items'] ?? null) ? $blogPayload['items'] : [];
    $pagination = is_array($blogPayload['pagination'] ?? null) ? $blogPayload['pagination'] : [];
    $totalPages = max(1, (int) ($pagination['total_pages'] ?? 1));

    foreach ($items as $item) {
        $slug = trim((string) ($item['slug'] ?? ''));
        if ($slug === '') {
            continue;
        }

        $lastmodRaw = trim((string) ($item['published_at'] ?? $item['updated_at'] ?? $item['created_at'] ?? ''));
        $lastmodTs = strtotime($lastmodRaw);
        $lastmod = $lastmodTs !== false ? gmdate('Y-m-d', (int) $lastmodTs) : $today;

        $entries[] = [
            'loc' => $siteBase . '/blog/' . rawurlencode($slug),
            'lastmod' => $lastmod,
        ];
    }

    $page += 1;
}

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
foreach ($entries as $entry) {
    $loc = kf_sitemap_xml_escape((string) ($entry['loc'] ?? ''));
    $lastmod = kf_sitemap_xml_escape((string) ($entry['lastmod'] ?? $today));
    echo "  <url>\n";
    echo "    <loc>{$loc}</loc>\n";
    echo "    <lastmod>{$lastmod}</lastmod>\n";
    echo "  </url>\n";
}
echo "</urlset>\n";
