<?php
declare(strict_types=1);

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

header('Content-Type: application/xml; charset=UTF-8');
header('X-Content-Type-Options: nosniff');

$siteOrigin = 'https://darpan.my.id';
$sections = function_exists('getContentSections') ? getContentSections() : [];

$xmlEscape = static function (string $val): string {
    return htmlspecialchars($val, ENT_XML1 | ENT_QUOTES, 'UTF-8');
};

$renderUrlNode = static function (
    string $loc,
    string $lastmod,
    string $changefreq,
    string $priority,
    ?string $enAlt = null,
    ?string $hiAlt = null
) use ($xmlEscape): string {
    $out = "  <url>\n";
    $out .= "    <loc>" . $xmlEscape($loc) . "</loc>\n";
    $out .= "    <lastmod>" . $xmlEscape($lastmod) . "</lastmod>\n";
    $out .= "    <changefreq>" . $xmlEscape($changefreq) . "</changefreq>\n";
    $out .= "    <priority>" . $xmlEscape($priority) . "</priority>\n";

    if ($enAlt !== null && $hiAlt !== null) {
        $out .= '    <xhtml:link rel="alternate" hreflang="en" href="' . $xmlEscape($enAlt) . "\" />\n";
        $out .= '    <xhtml:link rel="alternate" hreflang="hi" href="' . $xmlEscape($hiAlt) . "\" />\n";
        $out .= '    <xhtml:link rel="alternate" hreflang="x-default" href="' . $xmlEscape($enAlt) . "\" />\n";
    }

    $out .= "  </url>\n";
    return $out;
};

$nowIso = date('c');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
echo '        xmlns:xhtml="http://www.w3.org/1999/xhtml">' . "\n";

// 1. Homepage (EN & HI with alternates)
$homeEn = $siteOrigin . appUrl('index.php?lang=en');
$homeHi = $siteOrigin . appUrl('index.php?lang=hi');
echo $renderUrlNode($homeEn, $nowIso, 'daily', '1.0', $homeEn, $homeHi);
echo $renderUrlNode($homeHi, $nowIso, 'daily', '1.0', $homeEn, $homeHi);

// 2. Content Sections / Channels
foreach ($sections as $secKey => $secInfo) {
    $sSlug = rawurlencode(strtolower(trim((string) $secKey)));
    if ($sSlug === '') {
        continue;
    }
    $secEn = $siteOrigin . appUrl('index.php?lang=en&section=' . $sSlug);
    $secHi = $siteOrigin . appUrl('index.php?lang=hi&section=' . $sSlug);
    echo $renderUrlNode($secEn, $nowIso, 'daily', '0.8', $secEn, $secHi);
    echo $renderUrlNode($secHi, $nowIso, 'daily', '0.8', $secEn, $secHi);
}

// 3. Static / Policy Pages
$staticPages = ['about', 'editorial', 'disclaimer', 'privacy'];
foreach ($staticPages as $pKey) {
    $pEn = $siteOrigin . appUrl('page.php?lang=en&p=' . $pKey);
    $pHi = $siteOrigin . appUrl('page.php?lang=hi&p=' . $pKey);
    echo $renderUrlNode($pEn, $nowIso, 'monthly', '0.5', $pEn, $pHi);
    echo $renderUrlNode($pHi, $nowIso, 'monthly', '0.5', $pEn, $pHi);
}

// 4. Published Articles (/en/<slug> and /hi/<slug>)
if (isset($pdo)) {
    try {
        $stmt = $pdo->query("
            SELECT slug, created_at
            FROM articles
            WHERE status = 'published' AND slug != ''
            ORDER BY id DESC
        ");
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $art) {
            $slug = trim((string) ($art['slug'] ?? ''));
            if ($slug === '') {
                continue;
            }
            $encodedSlug = rawurlencode($slug);
            $artEn = $siteOrigin . appUrl('en/' . $encodedSlug);
            $artHi = $siteOrigin . appUrl('hi/' . $encodedSlug);

            $rawDate = (string) ($art['created_at'] ?? '');
            $ts = $rawDate !== '' ? strtotime($rawDate) : false;
            $lastmod = $ts ? date('c', $ts) : $nowIso;

            echo $renderUrlNode($artEn, $lastmod, 'weekly', '0.9', $artEn, $artHi);
            echo $renderUrlNode($artHi, $lastmod, 'weekly', '0.9', $artEn, $artHi);
        }
    } catch (Throwable $e) {
        error_log('Darpan sitemap articles query error: ' . $e->getMessage());
    }
}

echo "</urlset>\n";