<?php

declare(strict_types=1);

/**
 * 動態 sitemap：首頁、已審核店家、討論區主題（外掛啟用時）。
 */
header('Content-Type: application/xml; charset=UTF-8');

require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_seo.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';

$pdo = null;
try {
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
    }
} catch (Throwable) {
    $pdo = null;
}

/** @var list<array{loc:string,lastmod?:string,changefreq?:string,priority?:string}> */
$urls = [];

$urls[] = [
    'loc' => fate_absolute_url('index.php'),
    'changefreq' => 'daily',
    'priority' => '1.0',
];

if ($pdo instanceof PDO) {
    try {
        $st = $pdo->query(
            "SELECT spa_store_id, synced_at, created_at
             FROM spa_store_snapshots
             WHERE is_approved = 1
             ORDER BY spa_store_id ASC"
        );
        while ($st && ($row = $st->fetch(PDO::FETCH_ASSOC))) {
            $sid = (int) ($row['spa_store_id'] ?? 0);
            if ($sid <= 0) {
                continue;
            }
            $last = $row['synced_at'] ?? $row['created_at'] ?? null;
            $entry = [
                'loc' => fate_absolute_url('store.php?id=' . $sid),
                'changefreq' => 'weekly',
                'priority' => '0.8',
            ];
            if ($last !== null && $last !== false && trim((string) $last) !== '') {
                $ts = strtotime((string) $last);
                if ($ts !== false) {
                    $entry['lastmod'] = gmdate('Y-m-d', $ts);
                }
            }
            $urls[] = $entry;
        }
    } catch (Throwable) {
        // 略過店家列表
    }
}

if (fate_store_forum_plugin_active() && $pdo instanceof PDO) {
    $urls[] = [
        'loc' => fate_absolute_url('forum/index.php'),
        'changefreq' => 'hourly',
        'priority' => '0.9',
    ];
    try {
        $st = $pdo->query(
            "SELECT id, COALESCE(last_post_at, created_at) AS lm
             FROM fate_forum_threads
             WHERE is_hidden = 0
             ORDER BY id DESC
             LIMIT 5000"
        );
        while ($st && ($row = $st->fetch(PDO::FETCH_ASSOC))) {
            $tid = (int) ($row['id'] ?? 0);
            if ($tid <= 0) {
                continue;
            }
            $entry = [
                'loc' => fate_absolute_url('forum/thread.php?id=' . $tid),
                'changefreq' => 'daily',
                'priority' => '0.6',
            ];
            $last = $row['lm'] ?? null;
            if ($last !== null && trim((string) $last) !== '') {
                $ts = strtotime((string) $last);
                if ($ts !== false) {
                    $entry['lastmod'] = gmdate('Y-m-d', $ts);
                }
            }
            $urls[] = $entry;
        }
    } catch (Throwable) {
        // 略過論壇主題
    }
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as $u) {
    echo '  <url>' . "\n";
    echo '    <loc>' . htmlspecialchars($u['loc'], ENT_XML1 | ENT_COMPAT, 'UTF-8') . '</loc>' . "\n";
    if (!empty($u['lastmod'])) {
        echo '    <lastmod>' . htmlspecialchars($u['lastmod'], ENT_XML1 | ENT_COMPAT, 'UTF-8') . '</lastmod>' . "\n";
    }
    if (!empty($u['changefreq'])) {
        echo '    <changefreq>' . htmlspecialchars($u['changefreq'], ENT_XML1 | ENT_COMPAT, 'UTF-8') . '</changefreq>' . "\n";
    }
    if (!empty($u['priority'])) {
        echo '    <priority>' . htmlspecialchars($u['priority'], ENT_XML1 | ENT_COMPAT, 'UTF-8') . '</priority>' . "\n";
    }
    echo '  </url>' . "\n";
}
echo '</urlset>' . "\n";
