<?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 escXml(string $value): string
{
    $clean = preg_replace('/[^\x09\x0A\x0D\x20-\x{D7FF}\x{E000}-\x{FFFD}]/u', '', $value) ?? $value;
    $clean = str_ireplace(['<?php', '?>'], '', $clean);
    $clean = str_replace(['<', '>'], '', $clean);
    return htmlspecialchars(trim($clean), ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

function formatW3CDate(?string $dateStr): string
{
    $ts = ($dateStr !== null && trim($dateStr) !== '') ? strtotime($dateStr) : false;
    return ($ts === false) ? gmdate('c') : date('Y-m-d\TH:i:sP', $ts);
}

function buildSitemapUrl(string $origin, string $relativePath): string
{
    $built = trim((string) appUrl(ltrim($relativePath, '/')));
    if (preg_match('#^https?://#i', $built)) {
        return $built;
    }
    return rtrim($origin, '/') . '/' . ltrim($built, '/');
}

function renderUrlEntry(
    string $loc,
    string $enAlt,
    string $hiAlt,
    string $changefreq,
    string $priority,
    ?string $lastmod = null
): string {
    if ($loc === '' || !filter_var($loc, FILTER_VALIDATE_URL)) {
        return '';
    }

    $xml  = "  <url>\n";
    $xml .= "    <loc>" . escXml($loc) . "</loc>\n";
    $xml .= '    <xhtml:link rel="alternate" hreflang="en" href="' . escXml($enAlt) . "\" />\n";
    $xml .= '    <xhtml:link rel="alternate" hreflang="hi" href="' . escXml($hiAlt) . "\" />\n";
    $xml .= '    <xhtml:link rel="alternate" hreflang="x-default" href="' . escXml($enAlt) . "\" />\n";

    if ($lastmod !== null && $lastmod !== '') {
        $xml .= "    <lastmod>" . escXml($lastmod) . "</lastmod>\n";
    }

    $xml .= "    <changefreq>" . escXml($changefreq) . "</changefreq>\n";
    $xml .= "    <priority>" . escXml($priority) . "</priority>\n";
    $xml .= "  </url>\n\n";

    return $xml;
}

$sections = is_array(getContentSections()) ? getContentSections() : [];

$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) {
        error_log('sitemap.php articles query failed: ' . $e->getMessage());
    }
}

$xml  = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
$xml .= '        xmlns:xhtml="http://www.w3.org/1999/xhtml">' . "\n\n";

$enHome = buildSitemapUrl($origin, 'index.php?lang=en');
$hiHome = buildSitemapUrl($origin, 'index.php?lang=hi');
$xml .= renderUrlEntry($enHome, $enHome, $hiHome, 'daily', '1.0');
$xml .= renderUrlEntry($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 = buildSitemapUrl($origin, 'en/section/' . rawurlencode($secKey));
    $hiSec = buildSitemapUrl($origin, 'hi/section/' . rawurlencode($secKey));
    $xml .= renderUrlEntry($enSec, $enSec, $hiSec, 'daily', '0.85');
    $xml .= renderUrlEntry($hiSec, $enSec, $hiSec, 'daily', '0.85');
}

foreach (['about', 'privacy', 'disclaimer', 'editorial'] as $pageSlug) {
    $enPage = buildSitemapUrl($origin, 'en/page/' . $pageSlug);
    $hiPage = buildSitemapUrl($origin, 'hi/page/' . $pageSlug);
    $xml .= renderUrlEntry($enPage, $enPage, $hiPage, 'monthly', '0.5');
    $xml .= renderUrlEntry($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 = buildSitemapUrl($origin, 'en/' . rawurlencode($slug));
    $hiUrl = buildSitemapUrl($origin, 'hi/' . rawurlencode($slug));
    $dateSource = (string) (($art['updated_at'] ?? '') !== '' ? $art['updated_at'] : ($art['created_at'] ?? ''));
    $lastmod = formatW3CDate($dateSource);

    $xml .= renderUrlEntry($enUrl, $enUrl, $hiUrl, 'weekly', '0.8', $lastmod);
    $xml .= renderUrlEntry($hiUrl, $enUrl, $hiUrl, 'weekly', '0.8', $lastmod);
}

$xml .= "</urlset>\n";

$stray = (ob_get_level() > 0) ? ob_get_clean() : '';
if ($stray !== '') {
    error_log('sitemap.php stray output caught: ' . trim($stray));
}

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;