<?php // public/sitemap-index.xml
// Served as XML by the router when GET /sitemap-index.xml is requested.
// Main domain only - faculty subdomains receive 404.
declare(strict_types=1);

// Bootstrap (router already loaded these; require_once is idempotent)
require_once dirname(__DIR__) . '/app/config/constants.php';
require_once dirname(__DIR__) . '/app/config/database.php';
require_once dirname(__DIR__) . '/app/config/tenant.php';

if (TENANT !== 'main') {
    http_response_code(404);
    exit;
}

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

$base_domain = getenv('BASE_DOMAIN') ?: 'unizik.edu.ng';
$today       = date('Y-m-d');

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

// ── Main domain sitemap ───────────────────────────────────────────────────────
echo "  <sitemap>\n";
echo "    <loc>https://{$base_domain}/sitemap.xml</loc>\n";
echo "    <lastmod>{$today}</lastmod>\n";
echo "  </sitemap>\n";

// ── Faculty sitemaps ──────────────────────────────────────────────────────────
try {
    $faculties = Faculty::getAll();
    foreach ($faculties as $f) {
        $subdomain = $f->subdomain ?? '';
        if ($subdomain === '') {
            continue;
        }
        $loc = 'https://' . htmlspecialchars($subdomain, ENT_XML1 | ENT_QUOTES, 'UTF-8')
             . '.' . htmlspecialchars($base_domain, ENT_XML1 | ENT_QUOTES, 'UTF-8')
             . '/sitemap.xml';
        echo "  <sitemap>\n";
        echo "    <loc>{$loc}</loc>\n";
        echo "    <lastmod>{$today}</lastmod>\n";
        echo "  </sitemap>\n";
    }
} catch (\Throwable) {}

echo '</sitemapindex>' . "\n";
exit;
