<?php
/**
 * HappySchool — 動態 sitemap.xml 產生器
 * .htaccess 已設 SetHandler application/x-httpd-php，本檔以 PHP 執行，
 * 輸出 XML 供 Google 等搜尋引擎讀取。
 *
 * 內容：首頁 / about / browse / tag / gs / gs_article / 全部學校頁（三語 hreflang）
 * 產生後快取到 data/sitemap_cache.xml（schools.db 更新或 6 小時後重建）。
 */
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/happiness.php';
require_once __DIR__ . '/includes/gs_helper.php';

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

/* 正式網域：robots.txt 宣告 https://happyschool.hk */
$base = 'https://happyschool.hk';
$today = date('Y-m-d');

/* ---- 快取 ---- */
$cacheFile = __DIR__ . '/data/sitemap_cache.xml';
$dbFile    = __DIR__ . '/data/schools.db';
$stale = !is_file($cacheFile);
if (!$stale) {
    $cm = (int)@filemtime($cacheFile);
    if (is_file($dbFile) && (int)@filemtime($dbFile) > $cm) $stale = true;
    elseif ($cm < time() - 6 * 3600) $stale = true;
}
if ($stale) {
    $body = generate_sitemap($base, $today);
    if ($body !== null) {
        @file_put_contents($cacheFile, $body, LOCK_EX);
        echo $body;
        exit;
    }
    /* 產生失敗就退回舊快取 */
    if (is_file($cacheFile)) {
        readfile($cacheFile);
        exit;
    }
}
if (is_file($cacheFile)) {
    readfile($cacheFile);
}
exit;

function generate_sitemap(string $base, string $today): ?string
{
    try {
        $pdo = db();
        /* 每間學校一個 URL（取 TC 列代表，tier 三語相同） */
        $schools = $pdo->query("SELECT schoolid, tier FROM schools WHERE lang = 'tc' ORDER BY schoolid")->fetchAll(PDO::FETCH_ASSOC);

        $tags = array_keys(HAPPY_INDICATOR_DEFS);
        $tiers = ['kg', 'primary', 'secondary'];

        $gsAids = [];
        if (function_exists('gs_index')) {
            $idx = gs_index();
            if (is_array($idx)) {
                foreach (($idx['articles'] ?? []) as $a) {
                    $aid = (int) ($a['article_id'] ?? 0);
                    if ($aid > 0) $gsAids[] = $aid;
                }
            }
        }

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

        $staticPages = ['index.php', 'about.php', 'search.php', 'bookmarks.php'];
        foreach ($staticPages as $p) {
            echo "  <url>\n";
            echo "    <loc>{$base}/{$p}</loc>\n";
            echo "    <lastmod>{$today}</lastmod>\n";
            echo "  </url>\n";
        }

        /* browse.php（all + 3 階段）三語 */
        foreach (['', 'kg', 'primary', 'secondary'] as $t) {
            foreach (['tc', 'sc', 'en'] as $l) {
                $q = $t === '' ? "?lang={$l}" : "?tier={$t}&lang={$l}";
                echo "  <url>\n    <loc>{$base}/browse.php{$q}</loc>\n    <lastmod>{$today}</lastmod>\n  </url>\n";
            }
        }

        /* gs.php（all + 3 階段）三語 */
        foreach (['', 'kg', 'primary', 'secondary'] as $t) {
            foreach (['tc', 'sc', 'en'] as $l) {
                $q = $t === '' ? "?lang={$l}" : "?tier={$t}&lang={$l}";
                echo "  <url>\n    <loc>{$base}/gs.php{$q}</loc>\n    <lastmod>{$today}</lastmod>\n  </url>\n";
            }
        }

        /* tag.php：每 tag × 3 階段 × 3 語 */
        foreach ($tags as $tag) {
            foreach ($tiers as $t) {
                foreach (['tc', 'sc', 'en'] as $l) {
                    $q = "?tag={$tag}&tier={$t}&lang={$l}";
                    echo "  <url>\n    <loc>{$base}/tag.php{$q}</loc>\n    <lastmod>{$today}</lastmod>\n  </url>\n";
                }
            }
        }

        /* gs_article.php：每篇文章 × 3 語 */
        foreach ($gsAids as $aid) {
            foreach (['tc', 'sc', 'en'] as $l) {
                echo "  <url>\n    <loc>{$base}/gs_article.php?id={$aid}&amp;lang={$l}</loc>\n    <lastmod>{$today}</lastmod>\n  </url>\n";
            }
        }

        /* 學校頁：id + 三語 hreflang */
        foreach ($schools as $s) {
            $id = (int) $s['schoolid'];
            echo "  <url>\n";
            echo "    <loc>{$base}/school.php?id={$id}</loc>\n";
            echo "    <lastmod>{$today}</lastmod>\n";
            echo "    <xhtml:link rel=\"alternate\" hreflang=\"zh-Hant\" href=\"{$base}/school.php?id={$id}&amp;lang=tc\"/>\n";
            echo "    <xhtml:link rel=\"alternate\" hreflang=\"zh-Hans\" href=\"{$base}/school.php?id={$id}&amp;lang=sc\"/>\n";
            echo "    <xhtml:link rel=\"alternate\" hreflang=\"en\"      href=\"{$base}/school.php?id={$id}&amp;lang=en\"/>\n";
            echo "  </url>\n";
        }

        echo "</urlset>\n";
        return ob_get_clean();
    } catch (Throwable $e) {
        return null;
    }
}
