<?php
$seoMessage = '';
$seoMessageType = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAdminCsrfToken();
    $action = trim((string) ($_POST['seo_action'] ?? ''));

    if ($action === 'repair_dynamic_links') {
        $tables = ['article', 'product', 'page', 'download', 'video', 'recruit', 'image'];
        $updated = 0;
        foreach ($tables as $table) {
            $columns = $db->fetchAll("SHOW COLUMNS FROM {$db->table($table)}");
            $fieldMap = [];
            foreach ($columns as $column) {
                $fieldName = strtolower((string) ($column['Field'] ?? ''));
                if ($fieldName !== '') {
                    $fieldMap[$fieldName] = true;
                }
            }

            $contentField = '';
            foreach (['content', 'details', 'description', 'body'] as $candidate) {
                if (isset($fieldMap[$candidate])) {
                    $contentField = $candidate;
                    break;
                }
            }
            if ($contentField === '') {
                continue;
            }

            $rows = $db->fetchAll("SELECT id, {$contentField} AS content FROM {$db->table($table)} WHERE status = 1");
            foreach ($rows as $row) {
                $content = (string) ($row['content'] ?? '');
                if ($content === '') {
                    continue;
                }
                $repairResult = cmsRepairContentInternalLinks($content);
                if (!empty($repairResult['count']) && $repairResult['content'] !== $content) {
                    $db->update($table, [$contentField => $repairResult['content']], 'id = ?', [intval($row['id'])]);
                    $updated += intval($repairResult['count']);
                }
            }
        }
        $seoMessage = '已修复 ' . intval($updated) . ' 个正文内部链接。';
    } elseif ($action === 'generate_seo_files') {
        $files = cmsWriteSeoStaticFiles();
        $seoMessage = 'SEO 文件已生成：' . basename($files['sitemap']) . '、' . basename($files['robots']);
        if (!empty($files['indexnow_key_file'])) {
            $seoMessage .= '、' . basename($files['indexnow_key_file']);
        }
    } elseif ($action === 'push_indexnow') {
        $urls = array_column(cmsCollectSitemapUrls(), 'loc');
        $result = cmsPushUrlsToIndexNow($urls);
        $seoMessage = 'IndexNow 推送结果：' . (string) ($result['message'] ?? '');
        $seoMessageType = !empty($result['success']) ? 'success' : 'error';
    } elseif ($action === 'push_baidu') {
        $urls = array_column(cmsCollectSitemapUrls(), 'loc');
        $result = cmsPushUrlsToBaidu($urls);
        $seoMessage = '百度推送结果：' . (string) ($result['message'] ?? '');
        $seoMessageType = !empty($result['success']) ? 'success' : 'error';
    }
}

$brokenLinks = cmsDetectBrokenLinks(200);
$rewriteEnabled = cmsRewriteModeEnabled();
$internalLinkEnabled = cmsBoolConfigEnabled('seo_internal_link_enabled', false);
$indexNowEnabled = cmsBoolConfigEnabled('indexnow_enabled', false);
$baiduPushEnabled = cmsBoolConfigEnabled('baidu_push_enabled', false);
$sitemapUrl = cmsAbsoluteUrl('/sitemap.xml');
$robotsUrl = cmsAbsoluteUrl('/robots.txt');
$indexNowKey = trim((string) getSiteConfig('indexnow_key', ''));
$indexNowKeyUrl = $indexNowKey !== '' ? cmsAbsoluteUrl('/' . $indexNowKey . '.txt') : '';
?>
<div class="page-container fade-in">
    <div class="page-header">
        <div class="page-title">
            <div class="page-icon">
                <svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"></circle>
                    <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                </svg>
            </div>
            <div>
                <h1>SEO工具</h1>
                <p style="font-size:12px;color:#64748b;margin:0;">统一管理伪静态、智能内链、站点地图、主动推送和死链修复。</p>
            </div>
        </div>
    </div>

    <div class="site-page-overview">
        <div class="site-overview-item">
            <span class="overview-label">访问模式</span>
            <span class="overview-value"><?php echo $rewriteEnabled ? '伪静态' : '动态链接'; ?></span>
        </div>
        <div class="site-overview-item">
            <span class="overview-label">智能内链</span>
            <span class="overview-value"><?php echo $internalLinkEnabled ? '已开启' : '已关闭'; ?></span>
        </div>
        <div class="site-overview-item">
            <span class="overview-label">死链数量</span>
            <span class="overview-value"><?php echo count($brokenLinks); ?> 条</span>
        </div>
        <div class="site-overview-item">
            <span class="overview-label">主动推送</span>
            <span class="overview-value"><?php echo $indexNowEnabled || $baiduPushEnabled ? '可用' : '未开启'; ?></span>
        </div>
    </div>

    <?php if ($seoMessage !== ''): ?>
        <div class="alert alert-<?php echo $seoMessageType === 'error' ? 'danger' : 'success'; ?>" style="margin-bottom:16px;">
            <?php echo htmlspecialchars($seoMessage); ?>
        </div>
    <?php endif; ?>

    <div class="form-section">
        <div class="form-section-header">快速操作</div>
        <div class="form-section-body">
            <div style="display:flex;gap:12px;flex-wrap:wrap;">
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                    <input type="hidden" name="seo_action" value="repair_dynamic_links">
                    <button type="submit" class="btn btn-primary">修复正文内部链接</button>
                </form>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                    <input type="hidden" name="seo_action" value="generate_seo_files">
                    <button type="submit" class="btn btn-secondary">生成 Sitemap / Robots</button>
                </form>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                    <input type="hidden" name="seo_action" value="push_indexnow">
                    <button type="submit" class="btn btn-secondary">推送到 IndexNow</button>
                </form>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                    <input type="hidden" name="seo_action" value="push_baidu">
                    <button type="submit" class="btn btn-secondary">推送到百度</button>
                </form>
                <a href="/admin/main.php?act=site" class="btn btn-secondary">返回网站设置</a>
            </div>
            <p class="form-help" style="margin-top:10px;">会统一修复正文中的站内旧动态链接、旧静态链接、栏目旧链接，以及当前模式下不合适的内部链接。</p>
        </div>
    </div>

    <div class="form-section">
        <div class="form-section-header">站点地图与验证文件</div>
        <div class="form-section-body">
            <div style="display:grid;gap:8px;">
                <div class="form-help" style="margin:0;">Sitemap: <a href="<?php echo htmlspecialchars($sitemapUrl); ?>" target="_blank"><?php echo htmlspecialchars($sitemapUrl); ?></a></div>
                <div class="form-help" style="margin:0;">Robots: <a href="<?php echo htmlspecialchars($robotsUrl); ?>" target="_blank"><?php echo htmlspecialchars($robotsUrl); ?></a></div>
                <?php if ($indexNowKeyUrl !== ''): ?>
                    <div class="form-help" style="margin:0;">IndexNow Key: <a href="<?php echo htmlspecialchars($indexNowKeyUrl); ?>" target="_blank"><?php echo htmlspecialchars($indexNowKeyUrl); ?></a></div>
                <?php else: ?>
                    <div class="form-help" style="margin:0;">IndexNow Key: 开启 IndexNow 并保存网站设置后自动生成。</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="form-section">
        <div class="form-section-header">死链检测结果</div>
        <div class="form-section-body">
            <?php if (empty($brokenLinks)): ?>
                <div class="empty-state" style="padding:24px 0;color:#16a34a;">暂未发现可识别的内部坏链。</div>
            <?php else: ?>
                <div style="overflow:auto;">
                    <table class="table" style="width:100%;min-width:980px;">
                        <thead>
                            <tr>
                                <th>来源表</th>
                                <th>ID</th>
                                <th>标题</th>
                                <th>问题链接</th>
                                <th>问题类型</th>
                                <th>修复建议</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($brokenLinks as $item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars((string) $item['table']); ?></td>
                                    <td><?php echo intval($item['id']); ?></td>
                                    <td><?php echo htmlspecialchars((string) $item['title']); ?></td>
                                    <td style="max-width:280px;word-break:break-all;"><?php echo htmlspecialchars((string) $item['href']); ?></td>
                                    <td><?php echo htmlspecialchars((string) $item['issue']); ?></td>
                                    <td style="max-width:320px;word-break:break-word;"><?php echo htmlspecialchars((string) $item['suggestion']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
