<?php
declare(strict_types=1);

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

while (ob_get_level() > 0) {
    ob_end_clean();
}
ob_start();

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/sections-config.php';
require_once __DIR__ . '/includes/url-helper.php';

$isHttps = (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
    || (isset($_SERVER['SERVER_PORT']) && (int) $_SERVER['SERVER_PORT'] === 443)
    || (strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');
$scheme = $isHttps ? 'https' : 'http';
$host = preg_replace('/[^a-zA-Z0-9:.-]/', '', (string) ($_SERVER['HTTP_HOST'] ?? 'localhost')) ?: 'localhost';
$origin = $scheme . '://' . $host;

function cleanXmlText(string $value): string
{
    if (function_exists('mb_convert_encoding')) {
        $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
    }
    $clean = preg_replace('/[^\x09\x0A\x0D\x20-\x{D7FF}\x{E000}-\x{FFFD}]/u', '', $value);
    return trim((string) ($clean ?? $value));
}

function formatW3CDate(?string $dateStr): string
{
    if ($dateStr === null || trim($dateStr) === '') {
        return gmdate('c');
    }
    $ts = strtotime($dateStr);
    return ($ts === false) ? gmdate('c') : date('c', $ts);
}

function buildUrl(string $origin, string $relativePath): string
{
    $appPath = ltrim(appUrl(ltrim($relativePath, '/')), '/');
    return cleanXmlText($origin . '/' . $appPath);
}

$sections = getContentSections();
if (!is_array($sections)) {
    $sections = [];
}

$articles = [];
if (isset($pdo) && $pdo instanceof PDO) {
    try {
        $stmt = $pdo->query("
            SELECT slug, created_at, updated_at
            FROM articles
            WHERE status = 'published' AND slug != ''
            ORDER BY id DESC
        ");
        $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        try {
            $stmt = $pdo->query("
                SELECT slug, created_at
                FROM articles
                WHERE status = 'published' AND slug != ''
                ORDER BY id DESC
            ");
            $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Throwable $innerEx) {
            error_log('sitemap.php articles query failed: ' . $innerEx->getMessage());
        }
    }
}

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

$urlset = $dom->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset');
$urlset->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xhtml', 'http://www.w3.org/1999/xhtml');
$dom->appendChild($urlset);

$appendUrlNode = static function (
    string $loc,
    string $enAlt,
    string $hiAlt,
    string $changefreq,
    string $priority,
    ?string $lastmod = null
) use ($dom, $urlset): void {
    if (!filter_var($loc, FILTER_VALIDATE_URL)) {
        return;
    }

    $urlEl = $dom->createElement('url');
    $urlEl->appendChild($dom->createElement('loc', $loc));

    foreach (['en' => $enAlt, 'hi' => $hiAlt, 'x-default' => $enAlt] as $langCode => $hrefVal) {
        if (filter_var($hrefVal, FILTER_VALIDATE_URL)) {
            $linkEl = $dom->createElementNS('http://www.w3.org/1999/xhtml', 'xhtml:link');
            $linkEl->setAttribute('rel', 'alternate');
            $linkEl->setAttribute('hreflang', $langCode);
            $linkEl->setAttribute('href', $hrefVal);
            $urlEl->appendChild($linkEl);
        }
    }

    if ($lastmod !== null && $lastmod !== '') {
        $urlEl->appendChild($dom->createElement('lastmod', cleanXmlText($lastmod)));
    }

    $urlEl->appendChild($dom->createElement('changefreq', $changefreq));
    $urlEl->appendChild($dom->createElement('priority', $priority));
    $urlset->appendChild($urlEl);
};

$enHome = buildUrl($origin, 'index.php?lang=en');
$hiHome = buildUrl($origin, 'index.php?lang=hi');
$appendUrlNode($enHome, $enHome, $hiHome, 'daily', '1.0');
$appendUrlNode($hiHome, $enHome, $hiHome, 'daily', '1.0');

foreach (array_keys($sections) as $rawSecKey) {
    $secKey = preg_replace('/[^a-z0-9-]/', '', strtolower((string) $rawSecKey)) ?? '';
    if ($secKey === '') {
        continue;
    }
    $enSec = buildUrl($origin, 'en/section/' . rawurlencode($secKey));
    $hiSec = buildUrl($origin, 'hi/section/' . rawurlencode($secKey));
    $appendUrlNode($enSec, $enSec, $hiSec, 'daily', '0.85');
    $appendUrlNode($hiSec, $enSec, $hiSec, 'daily', '0.85');
}

foreach (['about', 'privacy', 'disclaimer', 'editorial'] as $pageSlug) {
    $enPage = buildUrl($origin, 'en/page/' . rawurlencode($pageSlug));
    $hiPage = buildUrl($origin, 'hi/page/' . rawurlencode($pageSlug));
    $appendUrlNode($enPage, $enPage, $hiPage, 'monthly', '0.5');
    $appendUrlNode($hiPage, $enPage, $hiPage, 'monthly', '0.5');
}

foreach ($articles as $art) {
    $slug = preg_replace('/[^a-z0-9-]/', '', strtolower(trim((string) ($art['slug'] ?? '')))) ?? '';
    if ($slug === '') {
        continue;
    }
    $enUrl = buildUrl($origin, 'en/' . rawurlencode($slug));
    $hiUrl = buildUrl($origin, 'hi/' . rawurlencode($slug));
    $dateSource = (string) (($art['updated_at'] ?? '') !== '' ? $art['updated_at'] : ($art['created_at'] ?? ''));
    $lastmod = formatW3CDate($dateSource);

    $appendUrlNode($enUrl, $enUrl, $hiUrl, 'weekly', '0.8', $lastmod);
    $appendUrlNode($hiUrl, $enUrl, $hiUrl, 'weekly', '0.8', $lastmod);
}

$xml = $dom->saveXML() ?: '';

// Remove any accidental PHP opening/closing tags in XML stream
$xml = preg_replace('/<\?php|\?>/i', '', $xml) ?? $xml;
// Ensure XML declaration at the top stays intact
if (!str_starts_with($xml, "<?xml")) {
    $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . $xml;
}

while (ob_get_level() > 0) {
    ob_end_clean();
}

if (!headers_sent()) {
    header_remove('Content-Type');
    header('Content-Type: application/xml; charset=UTF-8', true);
    header('X-Content-Type-Options: nosniff', true);
}

echo $xml;
exit;