<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

require __DIR__ . '/../../app/database.php';

$success = '';
$error = '';
$config = app_runtime_config();

$friendDefaults = array(
    'enabled' => false,
    'title' => '友情链接',
    'limit' => 8,
    'strategy' => 'random',
    'scope' => 'all',
    'include_domain_ids' => array(),
    'exclude_domain_ids' => array(),
    'custom_links' => array(),
    'wrapper_html' => '<div class="seo-friend-links" style="margin:32px auto 0;padding:18px 24px;max-width:1200px;font-size:13px;line-height:2;color:#64748b;"><h4 style="margin:0 0 8px;font-size:14px;color:#475569;">{{title}}</h4>{{links}}</div>'
);
$friendCfg = isset($config['friend_links']) && is_array($config['friend_links']) ? array_merge($friendDefaults, $config['friend_links']) : $friendDefaults;
if (!is_array($friendCfg['include_domain_ids'])) { $friendCfg['include_domain_ids'] = array(); }
if (!is_array($friendCfg['exclude_domain_ids'])) { $friendCfg['exclude_domain_ids'] = array(); }
if (!is_array($friendCfg['custom_links'])) { $friendCfg['custom_links'] = array(); }

$enabledDomainList = function_exists('list_enabled_domain_options') ? list_enabled_domain_options() : array();

$randomArticlesDefaults = array(
    'enabled' => false,
    'title' => '随便看看',
    'limit' => 10,
    'scope' => 'article_only',
    'pool_size' => 200,
    'per_domain_cap' => 2,
    'cross_site_ratio' => 70,
    'wrapper_html' => '<div class="side-card side-card-random-cross"><h3>{{title}}</h3><div class="random-article-list">{{links}}</div></div>'
);
$randomArticlesCfg = isset($config['random_articles']) && is_array($config['random_articles']) ? array_merge($randomArticlesDefaults, $config['random_articles']) : $randomArticlesDefaults;

$sitemapDefaults = array('enabled' => false);
$sitemapCfg = isset($config['sitemap']) && is_array($config['sitemap']) ? array_merge($sitemapDefaults, $config['sitemap']) : $sitemapDefaults;

$robotsCfg = isset($config['robots']) && is_array($config['robots']) ? $config['robots'] : array();
$robotsContent = isset($robotsCfg['content']) ? (string)$robotsCfg['content'] : '';

$pseudoStaticDefaults = array('enabled' => false);
$pseudoStaticCfg = isset($config['pseudo_static']) && is_array($config['pseudo_static']) ? array_merge($pseudoStaticDefaults, $config['pseudo_static']) : $pseudoStaticDefaults;

$seoHeadDefaults = array('enabled' => false);
$seoHeadCfg = isset($config['seo_head']) && is_array($config['seo_head']) ? array_merge($seoHeadDefaults, $config['seo_head']) : $seoHeadDefaults;

$internalLinkCfg = internal_link_config();
$internalLinks = list_internal_links();

$tab = isset($_GET['tab']) ? trim((string)$_GET['tab']) : 'general';
$validTabs = array('general', 'optimization', 'scheduler', 'analytics', 'maintenance', 'license');
if (!in_array($tab, $validTabs, true)) {
    $tab = 'general';
}

// 授权管理仅超管可见，普通用户跳转到通用设置
if ($tab === 'license' && !is_super_admin()) {
    $tab = 'general';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'license_action') {
    require_csrf();
    if (!is_super_admin()) {
        $error = '仅超级管理员可操作授权管理。';
    } else {
        $licOp = isset($_POST['op']) ? trim((string)$_POST['op']) : '';
        if ($licOp === 'verify') {
            $licResult = license_verify_remote();
            if ($licResult['valid'] === true) {
                $success = '授权验证通过，信息已更新。';
            } elseif ($licResult['valid'] === false) {
                $error = '验证失败：' . $licResult['msg'];
            } else {
                $error = '无法连接授权服务器，请稍后重试。';
            }
        } elseif ($licOp === 'deactivate') {
            app_update_runtime_config(array(license_config_key() => array()));
            $success = '本地授权信息已清除，请重新激活。';
        }
    }
    $config = app_runtime_config();
    $tab = 'license';
}

if ($tab === 'license' && isset($_GET['error']) && $_GET['error'] === 'expired' && $error === '') {
    $error = '授权已过期，后台功能已锁定，请在此页重新验证或清除授权。';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_analytics') {
    require_csrf();
    try {
        $analyticsCode = isset($_POST['analytics_code']) ? trim((string)$_POST['analytics_code']) : '';
        app_update_runtime_config(array('analytics_code' => $analyticsCode));
        $config = app_runtime_config();
        $success = $analyticsCode !== '' ? '流量统计代码已保存。' : '流量统计代码已清除。';
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'analytics';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_publish_settings') {
    require_csrf();
    try {
        $archivePageSize = isset($_POST['archive_page_size']) ? max(1, min(100, (int)$_POST['archive_page_size'])) : 10;
        app_update_runtime_config(array('archive_page_size' => $archivePageSize));
        $config = app_runtime_config();
        $success = '发布设置已保存。栏目页每页显示 ' . $archivePageSize . ' 篇文章。';
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'scheduler';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_scheduler_token') {
    require_csrf();
    try {
        $op = isset($_POST['op']) ? trim((string)$_POST['op']) : 'save';
        if ($op === 'generate') {
            $newToken = bin2hex(random_bytes(24));
            app_update_runtime_config(array('task_runner_token' => $newToken));
            $success = '已生成新的调度 Token。';
        } elseif ($op === 'clear') {
            app_update_runtime_config(array('task_runner_token' => ''));
            $success = '调度 Token 已清除，外部调度将被拒绝。';
        } else {
            $manualToken = isset($_POST['scheduler_token']) ? trim((string)$_POST['scheduler_token']) : '';
            app_update_runtime_config(array('task_runner_token' => $manualToken));
            $success = $manualToken !== '' ? '调度 Token 已保存。' : '调度 Token 已清空。';
        }
        $config = app_runtime_config();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'scheduler';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_friend_links') {
    require_csrf();
    try {
        $enabled = !empty($_POST['friend_enabled']);
        $title = isset($_POST['friend_title']) ? trim((string)$_POST['friend_title']) : '友情链接';
        if ($title === '') { $title = '友情链接'; }
        $limit = isset($_POST['friend_limit']) ? max(0, min(50, (int)$_POST['friend_limit'])) : 8;
        $strategyVal = isset($_POST['friend_strategy']) ? trim((string)$_POST['friend_strategy']) : 'random';
        $strategy = in_array($strategyVal, array('random', 'specified', 'blacklist'), true) ? $strategyVal : 'random';
        $scope = (isset($_POST['friend_scope']) && $_POST['friend_scope'] === 'homepage') ? 'homepage' : 'all';
        $includeIds = array();
        if (isset($_POST['friend_include']) && is_array($_POST['friend_include'])) {
            foreach ($_POST['friend_include'] as $id) {
                $idInt = (int)$id;
                if ($idInt > 0) { $includeIds[] = $idInt; }
            }
            $includeIds = array_values(array_unique($includeIds));
        }
        $excludeIds = array();
        if (isset($_POST['friend_exclude']) && is_array($_POST['friend_exclude'])) {
            foreach ($_POST['friend_exclude'] as $id) {
                $idInt = (int)$id;
                if ($idInt > 0) { $excludeIds[] = $idInt; }
            }
            $excludeIds = array_values(array_unique($excludeIds));
        }
        $customLinks = array();
        $linkNames = isset($_POST['friend_link_name']) && is_array($_POST['friend_link_name']) ? $_POST['friend_link_name'] : array();
        $linkUrls = isset($_POST['friend_link_url']) && is_array($_POST['friend_link_url']) ? $_POST['friend_link_url'] : array();
        foreach ($linkNames as $i => $n) {
            $n = trim((string)$n);
            $u = isset($linkUrls[$i]) ? trim((string)$linkUrls[$i]) : '';
            if ($n === '' || $u === '') { continue; }
            $customLinks[] = array('name' => $n, 'url' => $u);
        }
        $wrapperHtml = isset($_POST['friend_wrapper_html']) ? (string)$_POST['friend_wrapper_html'] : '';
        if (trim($wrapperHtml) === '') { $wrapperHtml = $friendDefaults['wrapper_html']; }
        app_update_runtime_config(array('friend_links' => array(
            'enabled' => $enabled,
            'title' => $title,
            'limit' => $limit,
            'strategy' => $strategy,
            'scope' => $scope,
            'include_domain_ids' => $includeIds,
            'exclude_domain_ids' => $excludeIds,
            'custom_links' => $customLinks,
            'wrapper_html' => $wrapperHtml
        )));
        $friendCfg = array(
            'enabled' => $enabled,
            'title' => $title,
            'limit' => $limit,
            'strategy' => $strategy,
            'scope' => $scope,
            'include_domain_ids' => $includeIds,
            'exclude_domain_ids' => $excludeIds,
            'custom_links' => $customLinks,
            'wrapper_html' => $wrapperHtml
        );
        $success = '站点互链配置已保存。';
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_random_articles') {
    require_csrf();
    try {
        $raEnabled = !empty($_POST['ra_enabled']);
        $raTitle = isset($_POST['ra_title']) ? trim((string)$_POST['ra_title']) : '随便看看';
        if ($raTitle === '') { $raTitle = '随便看看'; }
        $raLimit = isset($_POST['ra_limit']) ? max(1, min(30, (int)$_POST['ra_limit'])) : 10;
        $raScope = (isset($_POST['ra_scope']) && $_POST['ra_scope'] === 'all') ? 'all' : 'article_only';
        $raPool = isset($_POST['ra_pool_size']) ? max(20, min(500, (int)$_POST['ra_pool_size'])) : 200;
        $raCap = isset($_POST['ra_per_domain_cap']) ? max(0, min(10, (int)$_POST['ra_per_domain_cap'])) : 2;
        $raRatio = isset($_POST['ra_cross_site_ratio']) ? max(0, min(100, (int)$_POST['ra_cross_site_ratio'])) : 70;
        $raWrapperHtml = isset($_POST['ra_wrapper_html']) ? (string)$_POST['ra_wrapper_html'] : '';
        if (trim($raWrapperHtml) === '') { $raWrapperHtml = $randomArticlesDefaults['wrapper_html']; }
        app_update_runtime_config(array('random_articles' => array(
            'enabled' => $raEnabled,
            'title' => $raTitle,
            'limit' => $raLimit,
            'scope' => $raScope,
            'pool_size' => $raPool,
            'per_domain_cap' => $raCap,
            'cross_site_ratio' => $raRatio,
            'wrapper_html' => $raWrapperHtml
        )));
        $randomArticlesCfg = array(
            'enabled' => $raEnabled, 'title' => $raTitle, 'limit' => $raLimit,
            'scope' => $raScope, 'pool_size' => $raPool, 'per_domain_cap' => $raCap,
            'cross_site_ratio' => $raRatio, 'wrapper_html' => $raWrapperHtml
        );
        $success = '文章互链配置已保存。';
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_sitemap') {
    require_csrf();
    try {
        $smEnabled = !empty($_POST['sitemap_enabled']);
        app_update_runtime_config(array('sitemap' => array('enabled' => $smEnabled)));
        $sitemapCfg = array('enabled' => $smEnabled);
        $success = '站点地图配置已保存。' . ($smEnabled ? '已开启，需重新静态发布生效。' : '已关闭。');
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_robots') {
    require_csrf();
    try {
        $robotsTxt = isset($_POST['robots_content']) ? (string)$_POST['robots_content'] : '';
        if (trim($robotsTxt) === '' || !empty($_POST['robots_auto_generate'])) {
            $robotsTxt = generate_default_robots_txt();
        }
        app_update_runtime_config(array('robots' => array('content' => $robotsTxt)));
        $robotsContent = $robotsTxt;
        $success = 'robots.txt 配置已保存。';
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_pseudo_static') {
    require_csrf();
    try {
        $psEnabled = !empty($_POST['pseudo_static_enabled']);
        app_update_runtime_config(array('pseudo_static' => array('enabled' => $psEnabled)));
        $pseudoStaticCfg = array('enabled' => $psEnabled);
        $success = '伪静态配置已保存。' . ($psEnabled ? '已开启，动态页面将使用伪静态 URL。' : '已关闭。');
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_seo_head') {
    require_csrf();
    try {
        $shEnabled = !empty($_POST['seo_head_enabled']);
        app_update_runtime_config(array('seo_head' => array('enabled' => $shEnabled)));
        $seoHeadCfg = array('enabled' => $shEnabled);
        $success = 'SEO 增强配置已保存。' . ($shEnabled ? '已开启，页面将自动注入 SEO 元数据。' : '已关闭。');
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_internal_link_settings') {
    require_csrf();
    try {
        $ilEnabled = !empty($_POST['il_enabled']);
        $ilPriority = (isset($_POST['il_priority']) && $_POST['il_priority'] === 'external') ? 'external' : 'internal';
        $ilGlobalMax = isset($_POST['il_global_max']) ? max(0, min(50, (int)$_POST['il_global_max'])) : 3;
        $ilNofollow = !empty($_POST['il_nofollow']);
        $ilNewWindow = !empty($_POST['il_new_window']);
        app_update_runtime_config(array('internal_links' => array(
            'enabled' => $ilEnabled,
            'link_priority' => $ilPriority,
            'global_max_replace' => $ilGlobalMax,
            'nofollow_external' => $ilNofollow,
            'new_window' => $ilNewWindow
        )));
        $internalLinkCfg = array(
            'enabled' => $ilEnabled,
            'link_priority' => $ilPriority,
            'global_max_replace' => $ilGlobalMax,
            'nofollow_external' => $ilNofollow,
            'new_window' => $ilNewWindow
        );
        $success = '内链全局设置已保存。';
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_internal_link_keyword') {
    require_csrf();
    try {
        $ilId = isset($_POST['il_id']) ? (int)$_POST['il_id'] : 0;
        $ilData = array(
            'keyword' => isset($_POST['il_keyword']) ? trim((string)$_POST['il_keyword']) : '',
            'url' => isset($_POST['il_url']) ? trim((string)$_POST['il_url']) : '',
            'mode' => isset($_POST['il_mode']) ? (string)$_POST['il_mode'] : 'match',
            'max_replace' => isset($_POST['il_max_replace']) ? (int)$_POST['il_max_replace'] : 1,
            'priority' => isset($_POST['il_kw_priority']) ? (int)$_POST['il_kw_priority'] : 0,
            'status' => !empty($_POST['il_kw_status']) ? 'enabled' : 'disabled'
        );
        if ($ilData['keyword'] === '' || $ilData['url'] === '') {
            throw new Exception('关键词和链接地址不能为空。');
        }
        if ($ilId > 0) {
            $existing = find_internal_link_by_id($ilId);
            if (!$existing) { throw new Exception('记录不存在。'); }
            if (!is_super_admin() && (int)$existing['user_id'] !== current_user_id()) { throw new Exception('无权操作。'); }
            update_internal_link($ilId, $ilData);
            $success = '关键词链接已更新。';
        } else {
            create_internal_link($ilData);
            $success = '关键词链接已添加。';
        }
        $internalLinks = list_internal_links();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_internal_link') {
    require_csrf();
    try {
        $delId = isset($_POST['il_id']) ? (int)$_POST['il_id'] : 0;
        if ($delId <= 0) { throw new Exception('无效的记录 ID。'); }
        $existing = find_internal_link_by_id($delId);
        if (!$existing) { throw new Exception('记录不存在。'); }
        if (!is_super_admin() && (int)$existing['user_id'] !== current_user_id()) { throw new Exception('无权操作。'); }
        delete_internal_link($delId);
        $success = '关键词链接已删除。';
        $internalLinks = list_internal_links();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'batch_delete_internal_links') {
    require_csrf();
    try {
        $ids = isset($_POST['il_ids']) && is_array($_POST['il_ids']) ? $_POST['il_ids'] : array();
        $deleted = 0;
        foreach ($ids as $id) {
            $id = (int)$id;
            if ($id <= 0) continue;
            $existing = find_internal_link_by_id($id);
            if (!$existing) continue;
            if (!is_super_admin() && (int)$existing['user_id'] !== current_user_id()) continue;
            delete_internal_link($id);
            $deleted++;
        }
        $success = '已批量删除 ' . $deleted . ' 条关键词链接。';
        $internalLinks = list_internal_links();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'batch_import_internal_links') {
    require_csrf();
    try {
        $batchText = isset($_POST['il_batch_text']) ? trim((string)$_POST['il_batch_text']) : '';
        $batchMode = isset($_POST['il_batch_mode']) ? (string)$_POST['il_batch_mode'] : 'match';
        if ($batchText === '') { throw new Exception('请输入批量导入数据。'); }
        $lines = preg_split('/\r?\n/', $batchText);
        $imported = 0;
        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '' || strpos($line, '#') === 0) continue;
            $parts = preg_split('/[,\t|，]/', $line, 2);
            if (count($parts) < 2) continue;
            $kw = trim($parts[0]);
            $url = trim($parts[1]);
            if ($kw === '' || $url === '') continue;
            create_internal_link(array('keyword' => $kw, 'url' => $url, 'mode' => $batchMode));
            $imported++;
        }
        $success = '批量导入完成，成功导入 ' . $imported . ' 条。';
        $internalLinks = list_internal_links();
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
    $tab = 'optimization';
}

$optSubTab = isset($_GET['sub']) ? trim((string)$_GET['sub']) : 'friend_links';
$validOptSubs = array('friend_links', 'random_articles', 'internal_links', 'sitemap', 'robots', 'pseudo_static', 'seo_head', 'seo_backlinks');
if (!in_array($optSubTab, $validOptSubs, true)) { $optSubTab = 'friend_links'; }
if ($tab === 'optimization' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $pa = (string)$_POST['action'];
        if ($pa === 'save_friend_links') { $optSubTab = 'friend_links'; }
        elseif ($pa === 'save_random_articles') { $optSubTab = 'random_articles'; }
        elseif ($pa === 'save_internal_link_settings' || $pa === 'save_internal_link_keyword' || $pa === 'delete_internal_link' || $pa === 'batch_delete_internal_links' || $pa === 'batch_import_internal_links') { $optSubTab = 'internal_links'; }
        elseif ($pa === 'save_sitemap') { $optSubTab = 'sitemap'; }
        elseif ($pa === 'save_robots') { $optSubTab = 'robots'; }
        elseif ($pa === 'save_pseudo_static') { $optSubTab = 'pseudo_static'; }
        elseif ($pa === 'save_seo_head') { $optSubTab = 'seo_head'; }
    }
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 系统设置</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('settings', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">

            <header class="topbar">
                <div>
                    <h1>系统设置</h1>
                    <p>基础信息、系统优化与运维操作入口。伪静态规则请查看 <a href="/admin/settings/index.php?tab=optimization&sub=pseudo_static">系统优化 · 伪静态</a>。</p>
                </div>
            </header>

            <?php if ($error !== ''): ?>
                <div class="inline-alert is-error"><strong>保存失败</strong><span><?php echo e($error); ?></span></div>
            <?php endif; ?>
            <?php if ($success !== ''): ?>
                <div class="inline-alert is-success"><strong>保存成功</strong><span><?php echo e($success); ?></span></div>
            <?php endif; ?>

            <nav class="section-tabs settings-tabs">
                <a class="<?php echo $tab === 'general' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=general">基础信息</a>
                <a class="<?php echo $tab === 'optimization' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization">系统优化</a>
                <a class="<?php echo $tab === 'scheduler' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=scheduler">任务调度</a>
                <a class="<?php echo $tab === 'analytics' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=analytics">流量统计</a>
                <a class="<?php echo $tab === 'maintenance' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=maintenance">维护操作</a>
                <?php if (is_super_admin()): ?>
                <a class="<?php echo $tab === 'license' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=license">授权管理</a>
                <?php endif; ?>
            </nav>

            <?php if ($tab === 'general'): ?>
                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>基础信息</h2><p>系统当前运行的基本信息。</p></div></div>
                    <div class="settings-grid">
                        <div class="settings-item"><span>系统名称</span><strong><?php echo e(APP_NAME); ?></strong></div>
                        <div class="settings-item"><span>当前版本</span><strong><?php echo e(APP_VERSION); ?></strong></div>
                        <div class="settings-item"><span>开发者</span><strong><?php echo e(APP_DEVELOPER); ?></strong></div>
                        <div class="settings-item"><span>运行环境</span><strong>PHP <?php echo e(PHP_VERSION); ?></strong></div>
                        <div class="settings-item"><span>服务器时间</span><strong><?php echo e(date('Y-m-d H:i:s')); ?></strong></div>
                        <div class="settings-item"><span>站点入口</span><strong><?php echo e(isset($_SERVER['HTTP_HOST']) ? (string)$_SERVER['HTTP_HOST'] : '-'); ?></strong></div>
                    </div>
                </section>

                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>缓存策略</h2><p>默认缓存策略概览，后续可接入可视化配置。</p></div></div>
                    <div class="settings-grid">
                        <div class="settings-item"><span>页面缓存</span><strong>30 分钟</strong></div>
                        <div class="settings-item"><span>模板缓存</span><strong>12 小时</strong></div>
                        <div class="settings-item"><span>静态发布</span><strong>随内容更新触发</strong></div>
                    </div>
                </section>

            <?php endif; ?>

            <?php if ($tab === 'analytics'): ?>
                <section class="page-card settings-card">
                    <form method="post" action="/admin/settings/index.php?tab=analytics">
                        <input type="hidden" name="action" value="save_analytics">
                        <?php echo csrf_field(); ?>
                        <div class="card-head"><div><h2>流量统计代码</h2><p>粘贴第三方统计代码（如百度统计、Google Analytics），将自动注入所有页面的 &lt;/body&gt; 前。</p></div></div>
                        <div class="input-group" style="margin-top:12px;">
                            <span>统计代码</span>
                            <textarea class="input" name="analytics_code" rows="6" style="font-family:monospace;font-size:13px;line-height:1.6;resize:vertical;" placeholder="<script>&#10;var _hmt = _hmt || [];&#10;(function() { ... })();&#10;</script>"><?php echo e(isset($config['analytics_code']) ? (string)$config['analytics_code'] : ''); ?></textarea>
                        </div>
                        <p style="margin:8px 0 0;font-size:12.5px;color:#94a3b8;line-height:1.6;">支持 &lt;script&gt; 标签；保存后对动态页面立即生效，静态页面需重新发布。</p>
                        <div class="form-actions" style="margin-top:16px;">
                            <button class="btn-primary" type="submit">保存统计代码</button>
                        </div>
                    </form>
                </section>
            <?php endif; ?>

            <?php if ($tab === 'optimization'): ?>
                <style>
                    .opt-layout{display:grid;grid-template-columns:180px minmax(0,1fr);gap:0;align-items:flex-start;}
                    @media (max-width:860px){.opt-layout{grid-template-columns:1fr;}}
                    .opt-side-nav{display:flex;flex-direction:column;gap:2px;padding:4px 0;}
                    .opt-side-nav a{display:block;padding:10px 16px;border-radius:10px;font-size:14px;color:#475569;font-weight:500;text-decoration:none;transition:all .15s;}
                    .opt-side-nav a:hover{background:#f1f5f9;color:#1e293b;}
                    .opt-side-nav a.active{background:linear-gradient(135deg,#4f46e5,#6366f1);color:#fff;font-weight:700;box-shadow:0 4px 12px rgba(79,70,229,.2);}
                    .opt-panel{min-width:0;}
                    .switch-toggle{position:relative;display:inline-block;width:46px;height:24px;flex:0 0 auto;cursor:pointer;}
                    .switch-toggle input{opacity:0;width:0;height:0;position:absolute;}
                    .switch-toggle .slider{position:absolute;inset:0;background:#cbd5e1;border-radius:24px;transition:background .25s ease;}
                    .switch-toggle .slider::before{content:"";position:absolute;width:18px;height:18px;left:3px;top:3px;background:#fff;border-radius:50%;box-shadow:0 1px 3px rgba(15,23,42,.25);transition:transform .25s ease;}
                    .switch-toggle input:checked + .slider{background:#4f46e5;}
                    .switch-toggle input:checked + .slider::before{transform:translateX(22px);}
                    .switch-toggle input:focus-visible + .slider{box-shadow:0 0 0 3px rgba(79,70,229,.25);}
                    .opt-grid-3{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;align-items:flex-start;}
                    @media (max-width:680px){.opt-grid-3{grid-template-columns:1fr;}}
                    .opt-full{margin-top:14px;}
                    .card-hint{margin:10px 0 0;color:#94a3b8;font-size:12.5px;line-height:1.6;}
                    details.custom-links-panel{margin-top:14px;border-radius:12px;background:rgba(79,70,229,0.04);border:1px dashed rgba(79,70,229,0.35);overflow:hidden;}
                    details.custom-links-panel[open]{background:rgba(79,70,229,0.02);}
                    details.custom-links-panel > summary{list-style:none;cursor:pointer;padding:12px 14px;text-align:center;color:#4f46e5;font-size:14px;font-weight:500;user-select:none;}
                    details.custom-links-panel > summary::-webkit-details-marker{display:none;}
                    details.custom-links-panel > summary::before{content:"+ ";font-weight:600;}
                    details.custom-links-panel[open] > summary::before{content:"− ";}
                    details.custom-links-panel > summary:hover{background:rgba(79,70,229,0.08);}
                    .custom-links-body{padding:4px 14px 14px;}
                </style>
                <div class="opt-layout">
                <nav class="opt-side-nav">
                    <a class="<?php echo $optSubTab === 'friend_links' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=friend_links">站点互链</a>
                    <a class="<?php echo $optSubTab === 'random_articles' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=random_articles">文章互链</a>
                    <a class="<?php echo $optSubTab === 'internal_links' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=internal_links">内链管理</a>
                    <a class="<?php echo $optSubTab === 'sitemap' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=sitemap">站点地图</a>
                    <a class="<?php echo $optSubTab === 'robots' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=robots">robots</a>
                    <a class="<?php echo $optSubTab === 'pseudo_static' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=pseudo_static">伪静态</a>
                    <a class="<?php echo $optSubTab === 'seo_head' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=seo_head">SEO增强</a>
                    <a class="<?php echo $optSubTab === 'seo_backlinks' ? 'active' : ''; ?>" href="/admin/settings/index.php?tab=optimization&sub=seo_backlinks">超级外链</a>
                </nav>
                <div class="opt-panel">

                <?php if ($optSubTab === 'friend_links'): ?>
                <section class="page-card settings-card" style="margin:0;">
                    <form method="post" action="/admin/settings/index.php?tab=optimization" class="settings-form">
                        <input type="hidden" name="action" value="save_friend_links">
                        <?php echo csrf_field(); ?>
                        <div class="card-head">
                            <div><h2>站点互链（友情链接）</h2></div>
                            <label class="switch-toggle" title="开启 / 关闭">
                                <input type="checkbox" name="friend_enabled" value="1" <?php echo !empty($friendCfg['enabled']) ? 'checked' : ''; ?>>
                                <span class="slider"></span>
                            </label>
                        </div>
                        <div class="opt-grid-2">
                            <div class="input-group">
                                <span>最多显示数量</span>
                                <input class="input" type="number" name="friend_limit" min="0" max="50" value="<?php echo (int)$friendCfg['limit']; ?>" placeholder="0 不限">
                            </div>
                            <div class="input-group">
                                <span>选取策略</span>
                                <select class="select" name="friend_strategy" id="friendStrategy">
                                    <option value="random" <?php echo $friendCfg['strategy'] === 'random' ? 'selected' : ''; ?>>随机洗牌</option>
                                    <option value="specified" <?php echo $friendCfg['strategy'] === 'specified' ? 'selected' : ''; ?>>指定白名单</option>
                                    <option value="blacklist" <?php echo $friendCfg['strategy'] === 'blacklist' ? 'selected' : ''; ?>>指定黑名单</option>
                                </select>
                            </div>
                        </div>

                        <div class="input-group opt-full">
                            <span>显示范围</span>
                            <select class="select" name="friend_scope">
                                <option value="all" <?php echo (!isset($friendCfg['scope']) || $friendCfg['scope'] !== 'homepage') ? 'selected' : ''; ?>>全站显示（首页 + 文章 + 栏目页）</option>
                                <option value="homepage" <?php echo (isset($friendCfg['scope']) && $friendCfg['scope'] === 'homepage') ? 'selected' : ''; ?>>仅限首页显示</option>
                            </select>
                        </div>

                        <div class="input-group opt-full" id="friendIncludeWrap" style="<?php echo $friendCfg['strategy'] === 'specified' ? '' : 'display:none;'; ?>">
                            <span>白名单域名（仅在指定模式下生效）</span>
                            <select class="select" name="friend_include[]" multiple size="<?php echo max(4, min(8, count($enabledDomainList))); ?>" style="width:100%;">
                                <?php foreach ($enabledDomainList as $d): ?>
                                    <option value="<?php echo (int)$d['id']; ?>" <?php echo in_array((int)$d['id'], $friendCfg['include_domain_ids'], true) ? 'selected' : ''; ?>>
                                        <?php echo e($d['domain']); ?><?php if (!empty($d['site_name'])) { echo '（' . e($d['site_name']) . '）'; } ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="input-group opt-full" id="friendExcludeWrap" style="<?php echo $friendCfg['strategy'] === 'blacklist' ? '' : 'display:none;'; ?>">
                            <span>黑名单域名（选中的域名不参与友情链接）</span>
                            <select class="select" name="friend_exclude[]" multiple size="<?php echo max(4, min(8, count($enabledDomainList))); ?>" style="width:100%;">
                                <?php foreach ($enabledDomainList as $d): ?>
                                    <option value="<?php echo (int)$d['id']; ?>" <?php echo in_array((int)$d['id'], $friendCfg['exclude_domain_ids'], true) ? 'selected' : ''; ?>>
                                        <?php echo e($d['domain']); ?><?php if (!empty($d['site_name'])) { echo '（' . e($d['site_name']) . '）'; } ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <details class="custom-links-panel"<?php echo !empty($friendCfg['custom_links']) ? ' open' : ''; ?>>
                            <summary>添加自定义外链</summary>
                            <div class="custom-links-body">
                                <div id="friendCustomWrap" style="display:flex;flex-direction:column;gap:10px;">
                                    <?php
                                    $customList = $friendCfg['custom_links'];
                                    if (empty($customList)) { $customList = array(array('name' => '', 'url' => '')); }
                                    foreach ($customList as $item):
                                        $n = isset($item['name']) ? (string)$item['name'] : '';
                                        $u = isset($item['url']) ? (string)$item['url'] : '';
                                    ?>
                                        <div class="friend-custom-row" style="display:grid;grid-template-columns:auto minmax(140px,1fr) minmax(260px,2.4fr) auto;gap:8px;width:100%;align-items:center;">
                                            <input type="checkbox" class="friend-check" style="width:16px;height:16px;cursor:pointer;">
                                            <input class="input" type="text" name="friend_link_name[]" value="<?php echo e($n); ?>" placeholder="名称，如：百度">
                                            <input class="input" type="text" name="friend_link_url[]" value="<?php echo e($u); ?>" placeholder="https://example.com">
                                            <button class="btn-ghost friend-custom-remove" type="button">移除</button>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <div style="margin-top:8px;display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                                    <button class="btn-ghost" type="button" id="friendAddRow">+ 添加一条</button>
                                    <button class="btn-ghost" type="button" id="friendBatchBtn" style="color:#4f46e5;">批量添加</button>
                                    <button class="btn-ghost" type="button" id="friendBatchDelete" style="color:#dc2626;display:none;">批量删除</button>
                                    <label style="font-size:12px;color:#94a3b8;cursor:pointer;display:flex;align-items:center;gap:4px;"><input type="checkbox" id="friendCheckAll" style="width:14px;height:14px;"> 全选</label>
                                </div>
                                <div id="friendBatchPanel" style="display:none;margin-top:10px;">
                                    <textarea id="friendBatchText" class="input" rows="6" style="font-family:monospace;font-size:12px;line-height:1.8;width:100%;" placeholder="每行一条，格式：名称 URL&#10;例如：&#10;百度 https://www.baidu.com&#10;谷歌 https://www.google.com&#10;GitHub https://github.com"></textarea>
                                    <div style="margin-top:6px;display:flex;gap:8px;align-items:center;">
                                        <button class="btn-primary" type="button" id="friendBatchConfirm" style="font-size:13px;padding:6px 16px;">确认导入</button>
                                        <button class="btn-ghost" type="button" id="friendBatchCancel" style="font-size:13px;">取消</button>
                                        <span style="font-size:12px;color:#94a3b8;">支持空格或Tab分隔名称与URL</span>
                                    </div>
                                </div>
                            </div>
                        </details>

                        <div class="input-group opt-full">
                            <span>标题文字</span>
                            <input class="input" type="text" name="friend_title" value="<?php echo e($friendCfg['title']); ?>" placeholder="友情链接">
                        </div>

                        <div class="input-group opt-full">
                            <span>包裹模板 HTML <small style="color:#94a3b8;font-weight:400;">{{title}} = 标题文字 · {{links}} = 链接列表</small></span>
                            <textarea class="input" name="friend_wrapper_html" rows="4" style="font-family:monospace;font-size:12px;line-height:1.6;"><?php echo e(isset($friendCfg['wrapper_html']) ? $friendCfg['wrapper_html'] : $friendDefaults['wrapper_html']); ?></textarea>
                        </div>

                        <p class="card-hint">外链会在站内域名后面输出，不占用“最多显示数量”名额。当前已启用域名 <strong style="color:#475569;"><?php echo count($enabledDomainList); ?></strong> 个；改动后需重新静态发布生效。</p>

                        <div class="form-actions" style="margin-top:16px;">
                            <button class="btn-primary" type="submit">保存设置</button>
                        </div>
                    </form>
                </section>
                <?php endif; ?>

                <?php if ($optSubTab === 'random_articles'): ?>
                <section class="page-card settings-card" style="margin:0;">
                    <form method="post" action="/admin/settings/index.php?tab=optimization" class="settings-form">
                        <input type="hidden" name="action" value="save_random_articles">
                        <?php echo csrf_field(); ?>
                        <div class="card-head">
                            <div><h2>文章互链（随便看看）</h2></div>
                            <label class="switch-toggle" title="开启 / 关闭">
                                <input type="checkbox" name="ra_enabled" value="1" <?php echo !empty($randomArticlesCfg['enabled']) ? 'checked' : ''; ?>>
                                <span class="slider"></span>
                            </label>
                        </div>
                        <div class="opt-grid-2">
                            <div class="input-group">
                                <span>显示条数</span>
                                <input class="input" type="number" name="ra_limit" min="1" max="30" value="<?php echo (int)$randomArticlesCfg['limit']; ?>">
                            </div>
                            <div class="input-group">
                                <span>跨站比例（%）</span>
                                <input class="input" type="number" name="ra_cross_site_ratio" min="0" max="100" value="<?php echo (int)$randomArticlesCfg['cross_site_ratio']; ?>">
                            </div>
                        </div>

                        <div class="opt-grid-3" style="margin-top:14px;">
                            <div class="input-group">
                                <span>显示范围</span>
                                <select class="select" name="ra_scope">
                                    <option value="article_only" <?php echo $randomArticlesCfg['scope'] !== 'all' ? 'selected' : ''; ?>>仅文章页</option>
                                    <option value="all" <?php echo $randomArticlesCfg['scope'] === 'all' ? 'selected' : ''; ?>>全部页面</option>
                                </select>
                            </div>
                            <div class="input-group">
                                <span>每站配额</span>
                                <input class="input" type="number" name="ra_per_domain_cap" min="0" max="10" value="<?php echo (int)$randomArticlesCfg['per_domain_cap']; ?>">
                            </div>
                            <div class="input-group">
                                <span>时效池窗口</span>
                                <input class="input" type="number" name="ra_pool_size" min="20" max="500" value="<?php echo (int)$randomArticlesCfg['pool_size']; ?>">
                            </div>
                        </div>

                        <div class="input-group opt-full">
                            <span>标题文字</span>
                            <input class="input" type="text" name="ra_title" value="<?php echo e($randomArticlesCfg['title']); ?>" placeholder="随便看看">
                        </div>

                        <div class="input-group opt-full">
                            <span>包裹模板 HTML <small style="color:#94a3b8;font-weight:400;">{{title}} = 标题文字 · {{links}} = 文章链接列表</small></span>
                            <textarea class="input" name="ra_wrapper_html" rows="4" style="font-family:monospace;font-size:12px;line-height:1.6;"><?php echo e(isset($randomArticlesCfg['wrapper_html']) ? $randomArticlesCfg['wrapper_html'] : $randomArticlesDefaults['wrapper_html']); ?></textarea>
                        </div>

                        <p class="card-hint">跨站比例推荐 70；每站配额推荐 1-2（避免集中指向单站）；时效池推荐 100-300（越小新文章曝光越高）。修改后需重新静态发布生效。</p>

                        <div class="form-actions" style="margin-top:16px;">
                            <button class="btn-primary" type="submit">保存设置</button>
                        </div>
                    </form>
                </section>
                <?php endif; ?>

                <?php if ($optSubTab === 'internal_links'): ?>
                <!-- 内链全局设置 -->
                <section class="page-card settings-card" style="margin:0;">
                    <form method="post" action="/admin/settings/index.php?tab=optimization" class="settings-form">
                        <input type="hidden" name="action" value="save_internal_link_settings">
                        <?php echo csrf_field(); ?>
                        <div class="card-head">
                            <div><h2>内链设置</h2><p>开启后系统将对文章内容自动进行关键词链接处理，有助于提升站内 SEO 权重传递。</p></div>
                            <label class="switch-toggle" title="开启 / 关闭">
                                <input type="checkbox" name="il_enabled" value="1" <?php echo !empty($internalLinkCfg['enabled']) ? 'checked' : ''; ?>>
                                <span class="slider"></span>
                            </label>
                        </div>
                        <div class="opt-grid-3" style="margin-top:14px;">
                            <div class="input-group">
                                <span>链接优先级</span>
                                <select class="select" name="il_priority">
                                    <option value="internal" <?php echo (!isset($internalLinkCfg['link_priority']) || $internalLinkCfg['link_priority'] === 'internal') ? 'selected' : ''; ?>>站内优先</option>
                                    <option value="external" <?php echo (isset($internalLinkCfg['link_priority']) && $internalLinkCfg['link_priority'] === 'external') ? 'selected' : ''; ?>>站外优先</option>
                                </select>
                                <small style="color:#94a3b8;font-size:12px;margin-top:4px;">站内优先：匹配关键词时优先链接本站文章</small>
                            </div>
                            <div class="input-group">
                                <span>全局最大替换次数</span>
                                <input class="input" type="number" name="il_global_max" min="0" max="50" value="<?php echo (int)$internalLinkCfg['global_max_replace']; ?>">
                                <small style="color:#94a3b8;font-size:12px;margin-top:4px;">每个关键词在单篇文章的默认最大替换数</small>
                            </div>
                            <div class="input-group">
                                <span>SEO 属性</span>
                                <div style="display:flex;flex-direction:column;gap:8px;margin-top:4px;">
                                    <label style="display:flex;align-items:center;gap:8px;font-size:13px;color:#475569;cursor:pointer;">
                                        <input type="checkbox" name="il_nofollow" value="1" <?php echo !empty($internalLinkCfg['nofollow_external']) ? 'checked' : ''; ?>>
                                        外链添加 nofollow
                                    </label>
                                    <label style="display:flex;align-items:center;gap:8px;font-size:13px;color:#475569;cursor:pointer;">
                                        <input type="checkbox" name="il_new_window" value="1" <?php echo !empty($internalLinkCfg['new_window']) ? 'checked' : ''; ?>>
                                        外链新窗口打开
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions" style="margin-top:16px;">
                            <button class="btn-primary" type="submit">保存全局设置</button>
                        </div>
                    </form>
                </section>

                <!-- 关键词链接管理 -->
                <section class="page-card settings-card" style="margin-top:16px;">
                    <div class="card-head">
                        <div><h2>关键词链接管理</h2><p>添加自定义关键词与链接的映射关系。支持匹配替换和强制插入两种模式。</p></div>
                    </div>

                    <!-- 添加/编辑表单 -->
                    <form method="post" action="/admin/settings/index.php?tab=optimization" class="settings-form" id="ilKeywordForm">
                        <input type="hidden" name="action" value="save_internal_link_keyword">
                        <input type="hidden" name="il_id" id="ilEditId" value="0">
                        <?php echo csrf_field(); ?>
                        <div style="display:grid;grid-template-columns:minmax(120px,1fr) minmax(200px,2fr) 120px 80px 80px auto;gap:8px;align-items:end;">
                            <div class="input-group" style="margin:0;">
                                <span style="font-size:12px;">关键词</span>
                                <input class="input" type="text" name="il_keyword" id="ilKeyword" placeholder="如：SEO优化" required>
                            </div>
                            <div class="input-group" style="margin:0;">
                                <span style="font-size:12px;">链接地址</span>
                                <input class="input" type="text" name="il_url" id="ilUrl" placeholder="https://... 或 /path" required>
                            </div>
                            <div class="input-group" style="margin:0;">
                                <span style="font-size:12px;">出现方式</span>
                                <select class="select" name="il_mode" id="ilMode">
                                    <option value="match">匹配时出现</option>
                                    <option value="force">强制出现</option>
                                </select>
                            </div>
                            <div class="input-group" style="margin:0;">
                                <span style="font-size:12px;">替换次数</span>
                                <input class="input" type="number" name="il_max_replace" id="ilMaxReplace" min="0" max="50" value="1">
                            </div>
                            <div class="input-group" style="margin:0;">
                                <span style="font-size:12px;">优先级</span>
                                <input class="input" type="number" name="il_kw_priority" id="ilPriority" min="0" max="999" value="0">
                            </div>
                            <div style="display:flex;gap:6px;padding-bottom:1px;">
                                <label style="display:flex;align-items:center;gap:4px;font-size:12px;color:#475569;white-space:nowrap;cursor:pointer;" title="启用">
                                    <input type="checkbox" name="il_kw_status" value="1" id="ilStatus" checked> 启用
                                </label>
                                <button class="btn-primary" type="submit" style="padding:8px 16px;font-size:13px;" id="ilSubmitBtn">添加</button>
                                <button class="btn-ghost" type="button" style="padding:8px 12px;font-size:13px;display:none;" id="ilCancelBtn">取消</button>
                            </div>
                        </div>
                        <p style="margin:6px 0 0;font-size:12px;color:#94a3b8;">匹配时出现：文章中出现该关键词时替换为链接。强制出现：无论内容是否包含，自动在随机位置插入。替换次数为 0 表示不限。</p>
                    </form>

                    <!-- 关键词列表 -->
                    <?php if (!empty($internalLinks)): ?>
                    <div style="margin-top:16px;overflow-x:auto;">
                        <table style="width:100%;border-collapse:collapse;font-size:13px;">
                            <thead>
                                <tr style="background:#f8fafc;border-bottom:2px solid #e2e8f0;">
                                    <th style="padding:10px 8px;text-align:center;width:36px;"><input type="checkbox" id="ilCheckAll" style="width:15px;height:15px;cursor:pointer;"></th>
                                    <th style="padding:10px 12px;text-align:left;font-weight:600;color:#475569;">关键词</th>
                                    <th style="padding:10px 12px;text-align:left;font-weight:600;color:#475569;">链接地址</th>
                                    <th style="padding:10px 8px;text-align:center;font-weight:600;color:#475569;">模式</th>
                                    <th style="padding:10px 8px;text-align:center;font-weight:600;color:#475569;">次数</th>
                                    <th style="padding:10px 8px;text-align:center;font-weight:600;color:#475569;">优先级</th>
                                    <th style="padding:10px 8px;text-align:center;font-weight:600;color:#475569;">状态</th>
                                    <th style="padding:10px 12px;text-align:center;font-weight:600;color:#475569;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($internalLinks as $il): ?>
                                <tr style="border-bottom:1px solid #f1f5f9;" data-id="<?php echo (int)$il['id']; ?>" class="il-row" data-keyword="<?php echo e($il['keyword']); ?>" data-url="<?php echo e($il['url']); ?>" data-mode="<?php echo e($il['mode']); ?>" data-max="<?php echo (int)$il['max_replace']; ?>" data-priority="<?php echo (int)$il['priority']; ?>" data-status="<?php echo $il['status'] === 'enabled' ? '1' : '0'; ?>">
                                    <td style="padding:10px 8px;text-align:center;"><input type="checkbox" class="il-check" value="<?php echo (int)$il['id']; ?>" style="width:15px;height:15px;cursor:pointer;"></td>
                                    <td style="padding:10px 12px;font-weight:600;color:#1e293b;"><?php echo e($il['keyword']); ?></td>
                                    <td style="padding:10px 12px;color:#6366f1;word-break:break-all;max-width:280px;">
                                        <a href="<?php echo e($il['url']); ?>" target="_blank" rel="noopener" style="color:#6366f1;text-decoration:none;" title="<?php echo e($il['url']); ?>"><?php echo e(mb_strlen($il['url']) > 50 ? mb_substr($il['url'], 0, 50) . '...' : $il['url']); ?></a>
                                    </td>
                                    <td style="padding:10px 8px;text-align:center;">
                                        <span style="display:inline-block;padding:2px 10px;border-radius:999px;font-size:12px;<?php echo $il['mode'] === 'force' ? 'background:#fef3c7;color:#92400e;' : 'background:#dbeafe;color:#1e40af;'; ?>">
                                            <?php echo $il['mode'] === 'force' ? '强制' : '匹配'; ?>
                                        </span>
                                    </td>
                                    <td style="padding:10px 8px;text-align:center;color:#64748b;"><?php echo (int)$il['max_replace'] > 0 ? (int)$il['max_replace'] : '不限'; ?></td>
                                    <td style="padding:10px 8px;text-align:center;color:#64748b;"><?php echo (int)$il['priority']; ?></td>
                                    <td style="padding:10px 8px;text-align:center;">
                                        <span style="display:inline-block;width:8px;height:8px;border-radius:50%;<?php echo $il['status'] === 'enabled' ? 'background:#22c55e;' : 'background:#94a3b8;'; ?>"></span>
                                    </td>
                                    <td style="padding:10px 12px;text-align:center;white-space:nowrap;">
                                        <button class="btn-ghost il-edit-btn" type="button" style="padding:4px 10px;font-size:12px;">编辑</button>
                                        <form method="post" action="/admin/settings/index.php?tab=optimization" style="display:inline;">
                                            <input type="hidden" name="action" value="delete_internal_link">
                                            <input type="hidden" name="il_id" value="<?php echo (int)$il['id']; ?>">
                                            <?php echo csrf_field(); ?>
                                            <button class="btn-ghost" type="submit" style="padding:4px 10px;font-size:12px;color:#dc2626;" onclick="return confirm('确定删除？');">删除</button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <div style="margin-top:12px;display:flex;gap:8px;align-items:center;" id="ilBatchActions">
                            <form method="post" action="/admin/settings/index.php?tab=optimization" id="ilBatchDeleteForm" style="display:inline;">
                                <input type="hidden" name="action" value="batch_delete_internal_links">
                                <?php echo csrf_field(); ?>
                                <div id="ilBatchIdsWrap"></div>
                                <button class="btn-ghost" type="submit" id="ilBatchDeleteBtn" style="color:#dc2626;font-size:13px;display:none;" onclick="return confirm('确定批量删除选中的关键词链接？');">批量删除选中项</button>
                            </form>
                            <span id="ilSelectedCount" style="font-size:12px;color:#94a3b8;"></span>
                        </div>
                    </div>
                    <?php else: ?>
                    <div style="margin-top:16px;padding:24px;text-align:center;color:#94a3b8;font-size:14px;background:#f8fafc;border-radius:12px;">
                        暂无关键词链接，请在上方添加。
                    </div>
                    <?php endif; ?>
                </section>

                <!-- 批量导入 -->
                <section class="page-card settings-card" style="margin-top:16px;">
                    <details class="custom-links-panel">
                        <summary>批量导入关键词链接</summary>
                        <div class="custom-links-body">
                            <form method="post" action="/admin/settings/index.php?tab=optimization" class="settings-form">
                                <input type="hidden" name="action" value="batch_import_internal_links">
                                <?php echo csrf_field(); ?>
                                <div class="input-group" style="margin:0;">
                                    <span>每行一条，格式：<code>关键词,链接地址</code>（逗号、Tab、竖线分隔均可）</span>
                                    <textarea class="input" name="il_batch_text" rows="6" style="font-family:monospace;font-size:12px;line-height:1.6;" placeholder="SEO优化,https://example.com/seo&#10;网站建设,/jianzhan&#10;# 井号开头为注释行"></textarea>
                                </div>
                                <div class="input-group" style="margin-top:8px;">
                                    <span>默认模式</span>
                                    <select class="select" name="il_batch_mode" style="max-width:200px;">
                                        <option value="match">匹配时出现</option>
                                        <option value="force">强制出现</option>
                                    </select>
                                </div>
                                <div class="form-actions" style="margin-top:12px;">
                                    <button class="btn-primary" type="submit">批量导入</button>
                                </div>
                            </form>
                        </div>
                    </details>
                </section>

                <!-- 预览 -->
                <section class="page-card settings-card" style="margin-top:16px;">
                    <div class="card-head"><div><h2>效果预览</h2><p>输入一段文章内容，查看内链处理后的效果。</p></div></div>
                    <div class="input-group" style="margin-top:8px;">
                        <textarea class="input" id="ilPreviewInput" rows="4" style="font-size:13px;line-height:1.7;" placeholder="在此输入一段包含关键词的文章内容进行预览..."></textarea>
                    </div>
                    <div style="margin-top:8px;">
                        <button class="btn-soft" type="button" id="ilPreviewBtn">预览效果</button>
                    </div>
                    <div id="ilPreviewResult" style="display:none;margin-top:12px;padding:16px;background:#f8fafc;border-radius:12px;border:1px solid #e2e8f0;font-size:13px;line-height:1.8;">
                    </div>
                </section>
                <?php endif; ?>

                <?php if ($optSubTab === 'sitemap'): ?>
                <section class="page-card settings-card" style="margin:0;">
                    <form method="post" action="/admin/settings/index.php?tab=optimization&sub=sitemap" class="settings-form">
                        <input type="hidden" name="action" value="save_sitemap">
                        <?php echo csrf_field(); ?>
                        <div class="card-head">
                            <div><h2>站点地图</h2><p>开启后在每个站点页脚自动注入 XML 地图和 HTML 地图链接，方便搜索引擎抓取。</p></div>
                            <label class="switch-toggle" title="开启 / 关闭">
                                <input type="checkbox" name="sitemap_enabled" value="1" <?php echo !empty($sitemapCfg['enabled']) ? 'checked' : ''; ?>>
                                <span class="slider"></span>
                            </label>
                        </div>
                        <div style="margin-top:14px;padding:16px;background:#f8fafc;border-radius:12px;border:1px solid rgba(148,163,184,.14);">
                            <p style="margin:0 0 8px;font-size:13px;color:#334155;font-weight:600;">功能说明</p>
                            <ul style="margin:0;padding:0 0 0 18px;font-size:13px;color:#64748b;line-height:2;">
                                <li>开启后，系统会为每个已启用域名动态生成 <code>/sitemap.xml</code> 和 <code>/sitemap.html</code></li>
                                <li>页脚区域将自动注入地图导航链接：<code>&lt;a href="/sitemap.xml"&gt;XML地图&lt;/a&gt; | &lt;a href="/sitemap.html"&gt;网站地图&lt;/a&gt;</code></li>
                                <li><code>sitemap.xml</code> 遵循 <a href="https://www.sitemaps.org/protocol.html" target="_blank" rel="noopener" style="color:#4f46e5;">Sitemap 协议</a> 标准格式</li>
                                <li><code>sitemap.html</code> 为用户可读的网站地图页面</li>
                            </ul>
                        </div>
                        <p class="card-hint">修改后需重新静态发布生效（动态访问即时生效）。</p>
                        <div class="form-actions" style="margin-top:16px;">
                            <button class="btn-primary" type="submit">保存设置</button>
                        </div>
                    </form>
                </section>
                <?php endif; ?>

                <?php if ($optSubTab === 'robots'): ?>
                <section class="page-card settings-card" style="margin:0;">
                    <form method="post" action="/admin/settings/index.php?tab=optimization&sub=robots" class="settings-form">
                        <input type="hidden" name="action" value="save_robots">
                        <?php echo csrf_field(); ?>
                        <div class="card-head">
                            <div><h2>robots.txt 配置</h2><p>自动生成规范的 robots.txt，适用于所有绑定域名。也可手动编辑。</p></div>
                        </div>
                        <div class="input-group" style="margin-top:14px;">
                            <span>robots.txt 内容</span>
                            <textarea class="input" name="robots_content" rows="14" style="font-family:monospace;font-size:13px;line-height:1.7;resize:vertical;"><?php echo e($robotsContent !== '' ? $robotsContent : generate_default_robots_txt()); ?></textarea>
                        </div>
                        <p class="card-hint">留空或点击"自动生成"将根据当前已启用域名自动创建标准 robots.txt 模板。<strong>实际访问时，每个域名的 robots.txt 只会显示该域名自己的 Sitemap 地址</strong>，无需手动区分。</p>
                        <div class="form-actions" style="margin-top:16px;display:flex;gap:10px;">
                            <button class="btn-primary" type="submit">保存配置</button>
                            <button class="btn-soft" type="submit" name="robots_auto_generate" value="1">自动生成</button>
                        </div>
                    </form>
                </section>
                <?php endif; ?>

                <?php if ($optSubTab === 'pseudo_static'): ?>
                <?php
                    $nginxRewritePath = __DIR__ . '/../../nginx-rewrite.conf';
                    $nginxStaticRewritePath = __DIR__ . '/../../nginx-rewrite-static.conf';
                    $nginxStaticExamplePath = __DIR__ . '/../../config/nginx.static.conf.example';
                    $apacheRewritePath = __DIR__ . '/../../.htaccess';
                    $nginxRewriteContent = file_exists($nginxRewritePath) ? trim((string)file_get_contents($nginxRewritePath)) : '';
                    $nginxStaticRewriteContent = file_exists($nginxStaticRewritePath) ? trim((string)file_get_contents($nginxStaticRewritePath)) : '';
                    $apacheRewriteContent = file_exists($apacheRewritePath) ? trim((string)file_get_contents($apacheRewritePath)) : '';
                ?>
                <section class="page-card settings-card" style="margin:0;">
                    <form method="post" action="/admin/settings/index.php?tab=optimization&sub=pseudo_static" class="settings-form">
                        <input type="hidden" name="action" value="save_pseudo_static">
                        <?php echo csrf_field(); ?>
                        <div class="card-head">
                            <div>
                                <h2>伪静态 URL 模式</h2>
                                <p>本开关只控制<strong>前端模板生成的链接格式</strong>，不影响也不依赖服务器是否开启伪静态规则。</p>
                            </div>
                            <label class="switch-toggle" title="开启 / 关闭">
                                <input type="checkbox" name="pseudo_static_enabled" value="1" <?php echo !empty($pseudoStaticCfg['enabled']) ? 'checked' : ''; ?>>
                                <span class="slider"></span>
                            </label>
                        </div>
                        <div style="margin-top:14px;padding:16px;background:#f8fafc;border-radius:12px;border:1px solid rgba(148,163,184,.14);">
                            <p style="margin:0 0 10px;font-size:13px;color:#334155;font-weight:600;">两种模式对比</p>
                            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;font-size:13px;line-height:1.9;">
                                <div style="padding:14px;background:#fff;border-radius:10px;border:1px solid #e2e8f0;">
                                    <strong style="color:#16a34a;">✓ 开启（伪静态模式）</strong>
                                    <ul style="margin:8px 0 0;padding:0 0 0 18px;color:#475569;">
                                        <li>文章：<code>/wps/wps-2.html</code></li>
                                        <li>栏目：<code>/tiyu/</code></li>
                                        <li>标签：<code>/tag/foo/</code></li>
                                        <li>聚合：<code>/articles/</code></li>
                                    </ul>
                                    <p style="margin:8px 0 0;font-size:12px;color:#94a3b8;">⚠ 必须在 nginx/Apache 配置正确的伪静态规则才能访问，否则前端会 404。</p>
                                </div>
                                <div style="padding:14px;background:#fff;border-radius:10px;border:1px solid #e2e8f0;">
                                    <strong style="color:#4f46e5;">✗ 关闭（动态模式）</strong>
                                    <ul style="margin:8px 0 0;padding:0 0 0 18px;color:#475569;">
                                        <li>文章：<code>/index.php?slug=wps/wps-2</code></li>
                                        <li>栏目：<code>/index.php?slug=tiyu</code></li>
                                        <li>标签：<code>/index.php?slug=tag/foo</code></li>
                                        <li>聚合：<code>/index.php?slug=articles</code></li>
                                    </ul>
                                    <p style="margin:8px 0 0;font-size:12px;color:#94a3b8;">✓ 不依赖任何服务器重写规则，裸 PHP 即可访问；URL 略丑但永远能跑。</p>
                                </div>
                            </div>
                        </div>
                        <p class="card-hint" style="color:#b45309;">
                            ⚠ <strong>切换开关后需重新执行「全量静态发布」</strong>，否则旧静态 HTML 里的链接还是旧格式。系统也会在静态优先读取时自动跳过（开关 OFF 强制走 PHP 实时渲染）。
                        </p>
                        <div class="form-actions" style="margin-top:16px;">
                            <button class="btn-primary" type="submit">保存设置</button>
                        </div>
                    </form>
                </section>

                <section class="page-card settings-card" style="margin:16px 0 0;">
                    <div class="card-head"><div><h2>URL 规则说明</h2><p>平台按以下 URL 结构生成内容，部署时请确保服务器伪静态规则匹配。</p></div></div>
                    <div style="margin-top:12px;display:grid;grid-template-columns:auto 1fr;gap:6px 16px;font-size:13px;line-height:2;">
                        <code>/</code><span style="color:#64748b;">首页</span>
                        <code>/栏目名/</code><span style="color:#64748b;">栏目页（例如 <code>/tiyu/</code>）</span>
                        <code>/articles/</code><span style="color:#64748b;">全站文章聚合页</span>
                        <code>/栏目名/xxx.html</code><span style="color:#64748b;">文章详情页（例如 <code>/wps/wps-2.html</code>）</span>
                        <code>/tag/标签名/</code><span style="color:#64748b;">标签聚合页</span>
                        <code>/search?q=关键词</code><span style="color:#64748b;">站内搜索</span>
                        <code>/sitemap.xml</code><span style="color:#64748b;">XML 站点地图</span>
                        <code>/sitemap.html</code><span style="color:#64748b;">HTML 网站地图</span>
                        <code>/robots.txt</code><span style="color:#64748b;">搜索引擎协议文件</span>
                    </div>
                </section>

                <section class="page-card settings-card" style="margin:16px 0 0;">
                    <div class="card-head"><div><h2>Nginx / Apache / IIS 规则</h2><p>项目内已内置现成规则文件，按服务器类型选取即可。</p></div></div>
                    <div style="display:flex;gap:12px;flex-wrap:wrap;margin:14px 0;">
                        <button class="btn-primary" type="button" onclick="showPsRules('nginx_static')">⚡ Nginx 静态优先（推荐）</button>
                        <button class="btn-ghost" type="button" onclick="showPsRules('nginx')">Nginx 动态规则</button>
                        <button class="btn-ghost" type="button" onclick="showPsRules('apache')">Apache .htaccess 规则</button>
                        <span style="flex:1;"></span>
                        <button class="btn-soft" type="button" onclick="copyPsRules()">📋 复制当前规则</button>
                    </div>
                    <div style="margin-top:10px;font-size:13px;color:#475569;line-height:1.8;">
                        <p><strong>⚡ Nginx 静态优先（推荐）：</strong>命中静态文件时 0 PHP 开销直接返回，性能最佳。<strong>必须先在后台对每个域名执行「全量静态发布」</strong>生成 <code>site/{域名}/</code> 下的 HTML 文件后才会命中静态。系统在域名编辑保存（切换模板/域名/站点根）时自动清空旧静态，需重新发布。</p>
                        <p><strong>Nginx 动态版：</strong>适合不发布静态、纯 PHP 实时渲染模式。每次请求都进 PHP，方便调试但性能较差。</p>
                        <p><strong>Apache：</strong>项目根目录已提供 <code>.htaccess</code>，通常无需改动即可使用。</p>
                        <p><strong>IIS：</strong>项目根目录已提供 <code>web.config</code>，可直接用于 Windows IIS 重写。</p>
                    </div>
                    <div style="margin-top:16px;">
                        <p style="font-size:12.5px;color:#94a3b8;margin:0 0 6px;">当前显示：<span id="psRulesLabel" style="color:#4f46e5;font-weight:600;">⚡ Nginx 静态优先规则（<code>nginx-rewrite-static.conf</code>）</span></p>
                        <pre id="psNginxRules" style="margin:0;padding:14px 16px;background:#1e293b;color:#e2e8f0;border-radius:10px;font-size:12.5px;line-height:1.8;overflow-x:auto;white-space:pre-wrap;"><?php echo e($nginxStaticRewriteContent !== '' ? $nginxStaticRewriteContent : $nginxRewriteContent); ?></pre>
                    </div>
                    <p class="card-hint" style="margin-top:14px;" id="psRulesPath">文件路径：<code><?php echo e(str_replace('\\', '/', $nginxStaticRewritePath)); ?></code></p>
                </section>
                <script>
                var _psNginxStaticRules = <?php echo json_encode($nginxStaticRewriteContent, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
                var _psNginxRules = <?php echo json_encode($nginxRewriteContent, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
                var _psApacheRules = <?php echo json_encode($apacheRewriteContent, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
                var _psNginxStaticPath = <?php echo json_encode(str_replace('\\', '/', $nginxStaticRewritePath), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
                var _psNginxPath = <?php echo json_encode(str_replace('\\', '/', $nginxRewritePath), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
                var _psApachePath = <?php echo json_encode(str_replace('\\', '/', $apacheRewritePath), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
                var _psCurrentType = 'nginx_static';
                function showPsRules(type) {
                    _psCurrentType = type;
                    var pre = document.getElementById('psNginxRules');
                    var labelEl = document.getElementById('psRulesLabel');
                    var pathEl = document.getElementById('psRulesPath');
                    var text = '', label = '', path = '';
                    if (type === 'apache') {
                        text = _psApacheRules; label = 'Apache .htaccess 规则（<code>.htaccess</code>）'; path = _psApachePath;
                    } else if (type === 'nginx') {
                        text = _psNginxRules; label = 'Nginx 动态规则（<code>nginx-rewrite.conf</code>）'; path = _psNginxPath;
                    } else {
                        text = _psNginxStaticRules; label = '⚡ Nginx 静态优先规则（<code>nginx-rewrite-static.conf</code>）'; path = _psNginxStaticPath;
                    }
                    if (pre) { pre.textContent = text; }
                    if (labelEl) { labelEl.innerHTML = label; }
                    if (pathEl) { pathEl.innerHTML = '文件路径：<code>' + path + '</code>'; }
                }
                function copyPsRules() {
                    var text = _psCurrentType === 'apache' ? _psApacheRules : (_psCurrentType === 'nginx' ? _psNginxRules : _psNginxStaticRules);
                    if (!text) { alert('未找到可复制的规则内容。'); return; }
                    var label = _psCurrentType === 'apache' ? 'Apache' : (_psCurrentType === 'nginx' ? 'Nginx 动态' : 'Nginx 静态优先');
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(text).then(function() { alert(label + ' 规则已复制到剪贴板。'); }).catch(function() { _psFallbackCopy(text, label); });
                        return;
                    }
                    _psFallbackCopy(text, label);
                }
                function _psFallbackCopy(text, label) {
                    var ta = document.createElement('textarea');
                    ta.value = text; ta.style.position = 'absolute'; ta.style.left = '-9999px';
                    document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
                    alert(label + ' 规则已复制到剪贴板。');
                }
                </script>
                <?php endif; ?>

                <?php if ($optSubTab === 'seo_head'): ?>
                <section class="page-card settings-card" style="margin:0;">
                    <form method="post" action="/admin/settings/index.php?tab=optimization&sub=seo_head" class="settings-form">
                        <input type="hidden" name="action" value="save_seo_head">
                        <?php echo csrf_field(); ?>
                        <div class="card-head">
                            <div><h2>SEO 增强（自动注入）</h2><p>开启后系统将自动为所有页面注入 SEO 元数据，无需修改模板文件。</p></div>
                            <label class="switch-toggle" title="开启 / 关闭">
                                <input type="checkbox" name="seo_head_enabled" value="1" <?php echo !empty($seoHeadCfg['enabled']) ? 'checked' : ''; ?>>
                                <span class="slider"></span>
                            </label>
                        </div>

                        <div style="margin-top:16px;padding:18px 20px;background:#f8fafc;border-radius:12px;border:1px solid #e2e8f0;">
                            <h4 style="margin:0 0 12px;font-size:14px;color:#1e293b;">开启后自动注入以下内容：</h4>
                            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px 24px;font-size:13px;color:#475569;line-height:1.8;">
                                <div><strong style="color:#4f46e5;">✓</strong> Canonical URL（防重复收录）</div>
                                <div><strong style="color:#4f46e5;">✓</strong> Open Graph 社交分享标签</div>
                                <div><strong style="color:#4f46e5;">✓</strong> Article JSON-LD 结构化数据</div>
                                <div><strong style="color:#4f46e5;">✓</strong> BreadcrumbList 面包屑Schema</div>
                                <div><strong style="color:#4f46e5;">✓</strong> WebSite Schema（首页）</div>
                                <div><strong style="color:#4f46e5;">✓</strong> Robots meta 指令</div>
                                <div><strong style="color:#4f46e5;">✓</strong> 文章日期 &lt;time&gt; 语义标签</div>
                                <div><strong style="color:#4f46e5;">✓</strong> 关键词标签语义化包裹</div>
                            </div>
                        </div>

                        <div style="margin-top:16px;padding:14px 18px;background:#eff6ff;border-radius:10px;border:1px solid #bfdbfe;">
                            <h4 style="margin:0 0 8px;font-size:13px;color:#1d4ed8;">工作原理</h4>
                            <ul style="margin:0;padding-left:18px;font-size:12.5px;color:#1e40af;line-height:2;">
                                <li>系统在页面渲染时自动生成 <code>{{seo_head}}</code> 变量，包含 canonical / OG / JSON-LD 等标签</li>
                                <li>如模板已有 <code>{{seo_head}}</code> 占位符，将替换该位置；否则自动注入到 <code>&lt;/head&gt;</code> 前</li>
                                <li>所有模板（包括未来新增的）均自动生效，无需逐个修改模板文件</li>
                                <li>JSON-LD 结构化数据帮助搜索引擎生成富摘要（Rich Snippets），提升点击率</li>
                            </ul>
                        </div>

                        <div style="margin-top:16px;padding:14px 18px;background:#fefce8;border-radius:10px;border:1px solid #fde68a;">
                            <h4 style="margin:0 0 8px;font-size:13px;color:#92400e;">注意事项</h4>
                            <ul style="margin:0;padding-left:18px;font-size:12.5px;color:#78350f;line-height:2;">
                                <li>开启后对动态渲染页面立即生效；静态发布的页面需重新发布才能包含新的 SEO 标签</li>
                                <li>OG:image 优先使用文章封面图，如无封面图则不输出该标签</li>
                                <li>Canonical URL 基于当前访问域名自动拼接，确保域名已正确绑定</li>
                            </ul>
                        </div>

                        <div class="form-actions" style="margin-top:20px;">
                            <button class="btn-primary" type="submit">保存设置</button>
                        </div>
                    </form>
                </section>
                <?php endif; ?>

                <?php if ($optSubTab === 'seo_backlinks'): ?>
                <?php
                    $blFile = BASE_PATH . '/data/seo-links.txt';
                    $blTotal = is_file($blFile) ? count(file($blFile, FILE_SKIP_EMPTY_LINES)) : 0;
                    $blCliPath = str_replace('\\', '/', dirname(__DIR__)) . '/cli/seo-backlinks-runner-cli.php';
                ?>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;align-items:start;"><!-- @media handled below -->
                <section class="page-card settings-card" style="margin:0;">
                    <div class="card-head"><div><h2>后台任务</h2><p>自动遍历所有已发布域名，服务器后台执行，关闭浏览器不影响。</p></div></div>

                    <div style="margin-top:16px;">
                        <div class="input-group" style="max-width:280px;">
                            <span>每批条数</span>
                            <input class="input" type="number" id="seoBlBatchSize" value="15" min="1" max="30">
                        </div>
                        <div style="margin-top:16px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
                            <button class="btn-primary" type="button" id="seoBlStartBtn">启动任务</button>
                            <button class="btn-ghost" type="button" id="seoBlStopBtn" style="display:none;">停止任务</button>
                            <button class="btn-soft" type="button" id="seoBlResumeBtn" style="display:none;">继续任务</button>
                            <span id="seoBlMsg" style="font-size:13px;color:#64748b;"></span>
                        </div>
                    </div>

                    <div id="seoBlStatusPanel" style="display:none;margin-top:18px;">
                        <div style="padding:14px 18px;background:#f0fdf4;border-radius:10px;border:1px solid #bbf7d0;">
                            <div style="display:flex;gap:16px;flex-wrap:wrap;font-size:13px;color:#166534;">
                                <span>状态：<strong id="seoBlState">-</strong></span>
                                <span>域名：<strong id="seoBlDomainInfo">-</strong></span>
                                <span>进度：<strong id="seoBlPageInfo">-</strong></span>
                                <span>已发送：<strong id="seoBlSentInfo">0</strong> 条</span>
                            </div>
                            <div style="margin-top:10px;height:6px;background:#dcfce7;border-radius:6px;overflow:hidden;">
                                <div id="seoBlBar" style="height:100%;width:0%;background:linear-gradient(90deg,#22c55e,#16a34a);border-radius:6px;transition:width .3s;"></div>
                            </div>
                            <div style="margin-top:8px;font-size:12px;color:#64748b;">
                                启动时间：<span id="seoBlStartedAt">-</span> | 最近执行：<span id="seoBlLastRun">-</span>
                            </div>
                        </div>
                    </div>

                    <div style="margin-top:16px;" id="seoBlLogsWrap" hidden>
                        <h4 style="margin:0 0 8px;font-size:14px;color:#1e293b;">执行记录</h4>
                        <div style="overflow-y:auto;border:1px solid #e2e8f0;border-radius:10px;">
                            <table style="width:100%;border-collapse:collapse;font-size:12.5px;">
                                <thead style="position:sticky;top:0;background:#f8fafc;">
                                    <tr>
                                        <th style="padding:8px 10px;text-align:left;border-bottom:1px solid #e2e8f0;">时间</th>
                                        <th style="padding:8px 10px;text-align:left;border-bottom:1px solid #e2e8f0;">域名</th>
                                        <th style="padding:8px 10px;text-align:center;border-bottom:1px solid #e2e8f0;width:60px;">发送</th>
                                        <th style="padding:8px 10px;text-align:center;border-bottom:1px solid #e2e8f0;width:60px;">成功</th>
                                        <th style="padding:8px 10px;text-align:center;border-bottom:1px solid #e2e8f0;width:60px;">失败</th>
                                    </tr>
                                </thead>
                                <tbody id="seoBlLogsBody"></tbody>
                            </table>
                        </div>
                    </div>

                    <div style="margin-top:18px;padding:14px 18px;background:#eff6ff;border-radius:10px;border:1px solid #bfdbfe;">
                        <h4 style="margin:0 0 8px;font-size:13px;color:#1d4ed8;">计划任务配置</h4>
                        <p style="margin:0 0 8px;font-size:12.5px;color:#1e40af;line-height:1.8;">在宝塔面板添加 Shell 脚本计划任务，建议执行周期：<strong>每 1 分钟</strong>，脚本内容：</p>
                        <pre style="margin:0;padding:10px 14px;background:#1e293b;color:#e2e8f0;border-radius:8px;font-size:13px;overflow-x:auto;">php <?php echo e($blCliPath); ?></pre>
                        <p style="margin:8px 0 0;font-size:12px;color:#64748b;">每次 cron 调用处理一批（如 15 条），自动遍历所有已发布域名。任务完成后 cron 空转无消耗。</p>
                    </div>

                    <div style="margin-top:14px;padding:14px 18px;background:#fffbeb;border-radius:10px;border:1px solid #fde68a;">
                        <h4 style="margin:0 0 8px;font-size:13px;color:#92400e;">使用说明</h4>
                        <ul style="margin:0;padding-left:18px;font-size:12.5px;color:#78350f;line-height:2;">
                            <li>点击"启动任务"后，系统自动获取所有已发布内容的域名，依次处理</li>
                            <li>任务通过服务器后台 CLI 执行，关闭浏览器/刷新页面不影响进度</li>
                            <li>原理：利用站长工具类站点的查询缓存建立外链，属于正规 SEO 手段</li>
                            <li>当前外链库共 <strong><?php echo number_format($blTotal); ?></strong> 条模板</li>
                        </ul>
                    </div>
                </section>
                <section class="page-card settings-card" style="margin:0;">
                    <div class="card-head"><div><h2>手动执行</h2><p>选择单个域名在浏览器中立即推广，执行期间请勿关闭页面。</p></div></div>
                    <div style="margin-top:16px;">
                        <div class="opt-grid-2">
                            <div class="input-group">
                                <span>推广域名</span>
                                <select class="select" id="seoBlManualDomainSelect" style="width:100%;">
                                    <option value="">-- 从已绑定域名选择 --</option>
                                    <?php foreach ($enabledDomainList as $d): ?>
                                    <option value="<?php echo e(preg_replace('#^https?://#i', '', $d['domain'])); ?>"><?php echo e($d['domain']); ?><?php if (!empty($d['site_name'])) echo ' (' . e($d['site_name']) . ')'; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="input-group">
                                <span>或手动输入</span>
                                <input class="input" type="text" id="seoBlManualDomainInput" placeholder="example.com（不含 http://）">
                            </div>
                        </div>
                        <div class="opt-grid-2" style="margin-top:12px;">
                            <div class="input-group">
                                <span>每批条数</span>
                                <input class="input" type="number" id="seoBlManualNum" value="15" min="1" max="30">
                            </div>
                            <div class="input-group">
                                <span>批次间隔（秒）</span>
                                <input class="input" type="number" id="seoBlManualInterval" value="8" min="3" max="60">
                            </div>
                        </div>
                        <div style="margin-top:16px;display:flex;gap:10px;align-items:center;">
                            <button class="btn-primary" type="button" id="seoBlManualStart">开始推广</button>
                            <button class="btn-ghost" type="button" id="seoBlManualStop" style="display:none;">停止</button>
                            <span id="seoBlManualStatus" style="font-size:13px;color:#64748b;"></span>
                        </div>
                    </div>

                    <div id="seoBlManualProgress" style="display:none;margin-top:18px;padding:14px 18px;background:#f0fdf4;border-radius:10px;border:1px solid #bbf7d0;">
                        <div style="display:flex;gap:20px;font-size:13px;color:#166534;">
                            <span>总外链：<strong id="seoBlManualTotal">0</strong> 条</span>
                            <span>当前批次：<strong id="seoBlManualPage">0</strong> / <strong id="seoBlManualMaxPage">0</strong></span>
                            <span>已发送：<strong id="seoBlManualSent">0</strong> 条</span>
                        </div>
                        <div style="margin-top:10px;height:6px;background:#dcfce7;border-radius:6px;overflow:hidden;">
                            <div id="seoBlManualBar" style="height:100%;width:0%;background:linear-gradient(90deg,#22c55e,#16a34a);border-radius:6px;transition:width .3s;"></div>
                        </div>
                    </div>

                    <div style="margin-top:16px;overflow-y:auto;border:1px solid #e2e8f0;border-radius:10px;" id="seoBlManualResultWrap" hidden>
                        <table style="width:100%;border-collapse:collapse;font-size:12.5px;">
                            <thead style="position:sticky;top:0;background:#f8fafc;">
                                <tr>
                                    <th style="padding:8px 10px;text-align:left;border-bottom:1px solid #e2e8f0;width:40px;">ID</th>
                                    <th style="padding:8px 10px;text-align:left;border-bottom:1px solid #e2e8f0;width:140px;">推广URL</th>
                                    <th style="padding:8px 10px;text-align:left;border-bottom:1px solid #e2e8f0;">外链目标网址</th>
                                    <th style="padding:8px 10px;text-align:center;border-bottom:1px solid #e2e8f0;width:70px;">状态</th>
                                </tr>
                            </thead>
                            <tbody id="seoBlManualBody"></tbody>
                        </table>
                    </div>
                </section>
                </div><!-- end 2-col grid -->
                <style>
                @media (max-width:1100px) {
                    .opt-panel > div[style*="grid-template-columns:1fr 1fr"] { grid-template-columns:1fr !important; }
                }
                </style>

                <script>
                (function(){
                    var startBtn = document.getElementById('seoBlStartBtn');
                    var stopBtn = document.getElementById('seoBlStopBtn');
                    var resumeBtn = document.getElementById('seoBlResumeBtn');
                    var msgEl = document.getElementById('seoBlMsg');
                    var statusPanel = document.getElementById('seoBlStatusPanel');
                    var stateEl = document.getElementById('seoBlState');
                    var domainInfoEl = document.getElementById('seoBlDomainInfo');
                    var pageInfoEl = document.getElementById('seoBlPageInfo');
                    var sentInfoEl = document.getElementById('seoBlSentInfo');
                    var barEl = document.getElementById('seoBlBar');
                    var startedAtEl = document.getElementById('seoBlStartedAt');
                    var lastRunEl = document.getElementById('seoBlLastRun');
                    var logsWrap = document.getElementById('seoBlLogsWrap');
                    var logsBody = document.getElementById('seoBlLogsBody');
                    var batchInput = document.getElementById('seoBlBatchSize');
                    var pollTimer = null;

                    function postAction(action, extra) {
                        var fd = new FormData();
                        fd.append('action', action);
                        if (extra) { for (var k in extra) fd.append(k, extra[k]); }
                        return fetch('/admin/api/seo-backlinks-action.php', {method:'POST', body:fd}).then(function(r){return r.json();});
                    }

                    function fetchStatus() {
                        fetch('/admin/api/seo-backlinks-status.php').then(function(r){return r.json();}).then(function(data){
                            if (data.code !== 0) return;
                            renderStatus(data);
                        }).catch(function(){});
                    }

                    function renderStatus(s) {
                        var status = s.status || 'idle';
                        var stateLabels = {idle:'空闲', running:'运行中', stopped:'已停止', completed:'已完成'};
                        var stateColors = {idle:'#64748b', running:'#16a34a', stopped:'#d97706', completed:'#2563eb'};

                        stateEl.textContent = stateLabels[status] || status;
                        stateEl.style.color = stateColors[status] || '#64748b';

                        if (status === 'idle') {
                            statusPanel.style.display = 'none';
                            logsWrap.hidden = true;
                            startBtn.style.display = '';
                            stopBtn.style.display = 'none';
                            resumeBtn.style.display = 'none';
                            return;
                        }

                        statusPanel.style.display = '';
                        startBtn.style.display = status === 'running' ? 'none' : (status === 'completed' ? '' : 'none');
                        stopBtn.style.display = status === 'running' ? '' : 'none';
                        resumeBtn.style.display = status === 'stopped' ? '' : 'none';
                        if (status === 'completed') startBtn.textContent = '重新启动';
                        else startBtn.textContent = '启动任务';

                        var domains = s.domains || [];
                        var idx = s.current_domain_idx || 0;
                        var curDomain = idx < domains.length ? domains[idx] : (status === 'completed' ? '全部完成' : '-');
                        domainInfoEl.textContent = curDomain + ' (' + (Math.min(idx+1, domains.length)) + '/' + domains.length + ')';

                        var totalLinks = s.total_links || 0;
                        var batchSize = s.batch_size || 15;
                        var maxPage = totalLinks > 0 ? Math.ceil(totalLinks / batchSize) : 0;
                        var curPage = s.current_page || 0;
                        pageInfoEl.textContent = curPage + ' / ' + maxPage;

                        sentInfoEl.textContent = (s.total_sent || 0).toLocaleString();
                        startedAtEl.textContent = s.started_at || '-';
                        lastRunEl.textContent = s.last_run_at || '-';

                        // Progress bar: based on domain progress
                        var totalWork = domains.length * maxPage;
                        var doneWork = idx * maxPage + curPage;
                        var pct = totalWork > 0 ? Math.min(100, Math.round(doneWork / totalWork * 100)) : 0;
                        if (status === 'completed') pct = 100;
                        barEl.style.width = pct + '%';

                        // Logs
                        var logs = s.logs || [];
                        if (logs.length > 0) {
                            logsWrap.hidden = false;
                            logsBody.innerHTML = '';
                            for (var i = logs.length - 1; i >= 0; i--) {
                                var l = logs[i];
                                var tr = document.createElement('tr');
                                tr.innerHTML = '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;white-space:nowrap;">' + esc(l.time) + '</td>' +
                                    '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;">' + esc(l.domain) + '</td>' +
                                    '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;text-align:center;">' + l.sent + '</td>' +
                                    '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;text-align:center;color:#16a34a;">' + l.success + '</td>' +
                                    '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;text-align:center;color:#dc2626;">' + l.fail + '</td>';
                                logsBody.appendChild(tr);
                            }
                        } else {
                            logsWrap.hidden = true;
                        }

                        // Auto poll if running
                        if (status === 'running') {
                            if (!pollTimer) pollTimer = setInterval(fetchStatus, 10000);
                        } else {
                            if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
                        }
                    }

                    startBtn.addEventListener('click', function(){
                        var bs = Math.min(30, Math.max(1, parseInt(batchInput.value) || 15));
                        msgEl.textContent = '启动中...';
                        postAction('start', {batch_size: bs}).then(function(res){
                            msgEl.textContent = res.msg || '';
                            setTimeout(fetchStatus, 500);
                            if (!pollTimer) pollTimer = setInterval(fetchStatus, 10000);
                        }).catch(function(){ msgEl.textContent = '请求失败'; });
                    });

                    stopBtn.addEventListener('click', function(){
                        msgEl.textContent = '停止中...';
                        postAction('stop').then(function(res){
                            msgEl.textContent = res.msg || '';
                            fetchStatus();
                        }).catch(function(){ msgEl.textContent = '请求失败'; });
                    });

                    resumeBtn.addEventListener('click', function(){
                        msgEl.textContent = '恢复中...';
                        postAction('resume').then(function(res){
                            msgEl.textContent = res.msg || '';
                            setTimeout(fetchStatus, 500);
                            if (!pollTimer) pollTimer = setInterval(fetchStatus, 10000);
                        }).catch(function(){ msgEl.textContent = '请求失败'; });
                    });

                    function esc(s) {
                        var d = document.createElement('div');
                        d.appendChild(document.createTextNode(s || ''));
                        return d.innerHTML;
                    }

                    fetchStatus();
                })();
                </script>
                <script>
                (function(){
                    var domainSel = document.getElementById('seoBlManualDomainSelect');
                    var domainInput = document.getElementById('seoBlManualDomainInput');
                    var numInput = document.getElementById('seoBlManualNum');
                    var intervalInput = document.getElementById('seoBlManualInterval');
                    var startBtn = document.getElementById('seoBlManualStart');
                    var stopBtn = document.getElementById('seoBlManualStop');
                    var statusEl = document.getElementById('seoBlManualStatus');
                    var progressEl = document.getElementById('seoBlManualProgress');
                    var totalEl = document.getElementById('seoBlManualTotal');
                    var pageEl = document.getElementById('seoBlManualPage');
                    var maxPageEl = document.getElementById('seoBlManualMaxPage');
                    var sentEl = document.getElementById('seoBlManualSent');
                    var barEl = document.getElementById('seoBlManualBar');
                    var resultWrap = document.getElementById('seoBlManualResultWrap');
                    var tbody = document.getElementById('seoBlManualBody');
                    var timer = null;
                    var page = 0;
                    var sent = 0;
                    var running = false;

                    domainSel.addEventListener('change', function(){
                        if (this.value) domainInput.value = this.value;
                    });

                    function getDomain(){
                        var v = domainInput.value.trim();
                        if (!v && domainSel.value) v = domainSel.value;
                        return v.replace(/^https?:\/\//i, '').replace(/\/+$/, '');
                    }

                    function stop(){
                        running = false;
                        if (timer) { clearTimeout(timer); timer = null; }
                        startBtn.style.display = '';
                        stopBtn.style.display = 'none';
                        startBtn.textContent = '继续推广';
                        statusEl.textContent = '已停止';
                    }

                    stopBtn.addEventListener('click', stop);

                    startBtn.addEventListener('click', function(){
                        var domain = getDomain();
                        if (!domain) { statusEl.textContent = '请输入或选择域名'; return; }
                        if (startBtn.textContent === '开始推广') { page = 0; sent = 0; }
                        running = true;
                        startBtn.style.display = 'none';
                        stopBtn.style.display = '';
                        progressEl.style.display = '';
                        resultWrap.hidden = false;
                        statusEl.textContent = '运行中…';
                        fetchBatch(domain);
                    });

                    function fetchBatch(domain){
                        if (!running) return;
                        var num = Math.min(30, Math.max(1, parseInt(numInput.value) || 15));
                        var xhr = new XMLHttpRequest();
                        xhr.open('GET', '/admin/api/seo-links-data.php?p=' + page + '&num=' + num);
                        xhr.onload = function(){
                            if (!running) return;
                            try { var res = JSON.parse(xhr.responseText); } catch(e) { statusEl.textContent = '解析失败'; stop(); return; }
                            if (res.code === 1) {
                                statusEl.textContent = '全部完成！共发送 ' + sent + ' 条外链';
                                barEl.style.width = '100%';
                                stop();
                                startBtn.textContent = '开始推广';
                                return;
                            }
                            totalEl.textContent = res.count;
                            maxPageEl.textContent = res.maxPage;
                            pageEl.textContent = page + 1;
                            var urls = res.data || [];
                            tbody.innerHTML = '';
                            for (var i = 0; i < urls.length; i++) {
                                sent++;
                                var target = urls[i].replace(/\*\*\*/g, domain);
                                var tr = document.createElement('tr');
                                tr.innerHTML = '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;color:#64748b;">' + (i + 1) + '</td>' +
                                    '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;color:#475569;">' + escHtml(domain) + '</td>' +
                                    '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;word-break:break-all;"><a href="' + escHtml(target) + '" target="_blank" rel="noopener" style="color:#2563eb;text-decoration:none;">' + escHtml(target.length > 90 ? target.substring(0,90) + '...' : target) + '</a></td>' +
                                    '<td style="padding:6px 10px;border-bottom:1px solid #f1f5f9;text-align:center;" id="mst_' + sent + '"><span style="background:#dbeafe;color:#1d4ed8;padding:2px 8px;border-radius:10px;font-size:11px;">发布中</span></td>';
                                tbody.appendChild(tr);
                                pingUrl(target, sent);
                            }
                            sentEl.textContent = sent;
                            barEl.style.width = Math.min(100, Math.round(((page + 1) / res.maxPage) * 100)) + '%';
                            page++;
                            var interval = Math.max(3, parseInt(intervalInput.value) || 8);
                            timer = setTimeout(function(){ fetchBatch(domain); }, interval * 1000);
                        };
                        xhr.onerror = function(){ statusEl.textContent = '网络错误'; stop(); };
                        xhr.send();
                    }

                    function pingUrl(url, id){
                        var img = new Image();
                        img.onload = img.onerror = function(){
                            var el = document.getElementById('mst_' + id);
                            if (el) el.innerHTML = '<span style="background:#dcfce7;color:#166534;padding:2px 8px;border-radius:10px;font-size:11px;">成功</span>';
                        };
                        img.src = url;
                    }

                    function escHtml(s){
                        var d = document.createElement('div');
                        d.appendChild(document.createTextNode(s));
                        return d.innerHTML;
                    }
                })();
                </script>
                <?php endif; ?>

                </div>
                </div>
            <?php endif; ?>

            <?php if ($tab === 'scheduler'): ?>
                <?php $currentToken = task_runner_token(); ?>
                <?php $cliScriptPath = str_replace('\\', '/', dirname(__DIR__, 2)) . '/admin/cli/article-task-runner-cli.php'; ?>
                <?php $archivePageSize = isset($config['archive_page_size']) ? (int)$config['archive_page_size'] : 10; ?>

                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>发布设置</h2><p>控制栏目页（分类归档页）的文章分页数量等参数。</p></div></div>
                    <form method="post" action="/admin/settings/index.php?tab=scheduler">
                        <input type="hidden" name="action" value="save_publish_settings">
                        <?php echo csrf_field(); ?>
                        <div class="input-group" style="max-width:360px;">
                            <span>栏目页每页文章数</span>
                            <input class="input" type="number" name="archive_page_size" min="1" max="100" value="<?php echo (int)$archivePageSize; ?>" placeholder="默认10">
                        </div>
                        <p style="margin:8px 0 0;font-size:12.5px;color:#94a3b8;line-height:1.6;">设置栏目归档页每页显示的文章数量（1~100），默认为 10。修改后对动态页面立即生效，静态页面需重新发布。</p>
                        <div class="form-actions" style="margin-top:16px;">
                            <button class="btn-primary" type="submit">保存发布设置</button>
                        </div>
                    </form>
                </section>

                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>推荐方式：CLI 调度（Shell 脚本）</h2><p>通过 PHP CLI 直接运行任务脚本，无需 HTTP 请求，不受 Nginx 超时限制，稳定可靠。</p></div></div>
                    <div class="help-body">
                        <p style="margin:0 0 10px;font-size:13px;color:#64748b;font-weight:600;">宝塔计划任务配置：</p>
                        <p>任务类型选择 <strong>Shell 脚本</strong>，执行周期设为 <strong>每 1 分钟</strong>，脚本内容：</p>
                        <pre style="margin:8px 0 0;padding:12px 14px;background:#1e293b;color:#e2e8f0;border-radius:8px;font-size:13px;line-height:1.7;overflow-x:auto;">php <?php echo e($cliScriptPath); ?></pre>
                    </div>
                    <div style="margin-top:16px;padding:14px 16px;background:rgba(99,102,241,.06);border-radius:10px;border:1px solid rgba(99,102,241,.15);">
                        <p style="margin:0;font-size:12.5px;color:#6366f1;line-height:1.8;">
                            <strong>优势：</strong>CLI 模式无需 Token 鉴权（仅限服务器本地执行）、不受 HTTP 超时影响、内置文件锁防并发。<br>
                            日志文件：<code>runtime/article-task-runner.log</code>
                        </p>
                    </div>
                    <div style="margin-top:14px;">
                        <p style="font-size:13px;color:#64748b;font-weight:600;">Linux crontab 示例：</p>
                        <pre style="margin:6px 0 0;padding:12px 14px;background:#1e293b;color:#e2e8f0;border-radius:8px;font-size:13px;line-height:1.7;overflow-x:auto;">* * * * * php <?php echo e($cliScriptPath); ?> >> /dev/null 2>&1</pre>
                    </div>
                </section>

                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>备选方式：HTTP 调度 Token</h2><p>如需通过 HTTP 请求触发（如第三方监控平台调用 <code>admin/cli/article-task-runner.php</code>），需携带此 Token 进行鉴权。</p></div></div>
                    <form method="post" action="/admin/settings/index.php?tab=scheduler">
                        <input type="hidden" name="action" value="save_scheduler_token">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="op" value="save">
                        <div class="input-group" style="max-width:600px;">
                            <span>当前 Token</span>
                            <div style="display:flex;gap:8px;">
                                <input class="input" type="text" name="scheduler_token" id="schedulerToken" value="<?php echo e($currentToken); ?>" placeholder="点击右侧按钮生成，或手动输入" style="flex:1;font-family:monospace;">
                                <button class="btn-ghost" type="button" id="btnCopyToken" title="复制">复制</button>
                            </div>
                        </div>
                        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:16px;">
                            <button class="btn-primary" type="submit">保存 Token</button>
                            <button class="btn-soft" type="submit" name="op" value="generate">随机生成新 Token</button>
                            <button class="btn-ghost" type="submit" name="op" value="clear" onclick="return confirm('清除后外部调度将被拒绝，确定？');">清除 Token</button>
                        </div>
                    </form>
                    <?php if ($currentToken !== ''): ?>
                    <div style="margin-top:20px;padding:16px;background:#f8fafc;border-radius:12px;border:1px solid rgba(148,163,184,.14);">
                        <p style="margin:0 0 8px;font-size:13px;color:#64748b;font-weight:600;">HTTP POST 参数示例：</p>
                        <pre style="margin:0;padding:12px 14px;background:#1e293b;color:#e2e8f0;border-radius:8px;font-size:13px;line-height:1.7;overflow-x:auto;">limit=1&token=<?php echo e($currentToken); ?></pre>
                    </div>
                    <?php endif; ?>
                    <p style="margin-top:14px;font-size:12.5px;color:#94a3b8;line-height:1.7;">Token 支持通过 POST 参数 <code>token</code>、GET 参数 <code>token</code> 或请求头 <code>X-Task-Token</code> 传递。本机 / CLI / 已登录会话无需 Token。详细配置请参考 <a href="help.php?tab=scheduler">使用帮助 · 任务调度</a>。</p>
                </section>
            <?php endif; ?>

            <?php if ($tab === 'license'): ?>
                <?php
                    $lic = license_config();
                    $licActive = license_is_activated();
                    $licExpired = license_is_expired();
                    $licCodeRaw = isset($lic['activation_code']) ? (string)$lic['activation_code'] : '';
                    $licCodeDisplay = $licCodeRaw !== '' ? $licCodeRaw : '-';
                ?>
                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>授权信息</h2><p>当前系统的授权状态与详细信息。</p></div></div>
                    <?php if ($licExpired): ?>
                    <div style="background:#fef2f2;border:1px solid #fecaca;border-radius:10px;padding:18px 20px;margin-bottom:20px;text-align:center;">
                        <p style="margin:0;font-size:16px;font-weight:700;color:#991b1b;">⚠ 授权已过期，系统功能已锁定</p>
                        <p style="margin:6px 0 0;font-size:13px;color:#991b1b;">请联系管理员延期后点击"重新验证"，或清除授权后使用新激活码重新激活。</p>
                    </div>
                    <div class="settings-grid" style="opacity:0.7;">
                        <div class="settings-item"><span>激活码</span><strong style="font-family:monospace;letter-spacing:1px;"><?php echo e($licCodeDisplay); ?></strong></div>
                        <div class="settings-item"><span>授权状态</span><strong style="color:#dc2626;"><?php echo e(license_status_label()); ?></strong></div>
                        <div class="settings-item"><span>截止日期</span><strong style="color:#dc2626;"><?php echo e(license_end_date_display_text($lic)); ?></strong></div>
                        <div class="settings-item"><span>上次验证</span><strong><?php echo !empty($lic['last_verify_at']) ? date('Y-m-d H:i:s', (int)$lic['last_verify_at']) : '-'; ?></strong></div>
                    </div>
                    <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:20px;">
                        <form method="post" action="/admin/settings/index.php?tab=license">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="action" value="license_action">
                            <input type="hidden" name="op" value="verify">
                            <button class="btn-primary" type="submit">重新验证</button>
                        </form>
                        <form method="post" action="/admin/settings/index.php?tab=license" onsubmit="return confirm('确定要清除本地授权信息吗？清除后可使用新激活码。');">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="action" value="license_action">
                            <input type="hidden" name="op" value="deactivate">
                            <button class="btn-ghost" type="submit" style="color:#dc2626;">清除授权</button>
                        </form>
                        <a class="btn-soft" href="/activate.php">前往激活页</a>
                    </div>
                    <?php elseif ($licActive): ?>
                    <div class="settings-grid">
                        <div class="settings-item"><span>激活码</span><strong style="font-family:monospace;letter-spacing:1px;"><?php echo e($licCodeDisplay); ?></strong></div>
                        <div class="settings-item"><span>授权状态</span><strong style="color:<?php echo (isset($lic['status']) && $lic['status'] === 'active') ? '#15803d' : '#dc2626'; ?>;"><?php echo e(license_status_label()); ?></strong></div>
                        <div class="settings-item"><span>被授权方</span><strong><?php echo e(!empty($lic['licensee']) ? $lic['licensee'] : (!empty($lic['username']) ? $lic['username'] : '-')); ?></strong></div>
                        <div class="settings-item"><span>授权域名</span><strong><?php echo e(!empty($lic['domain']) ? $lic['domain'] : request_host()); ?></strong></div>
                        <div class="settings-item"><span>授权分类</span><strong><?php echo e(!empty($lic['category']) ? $lic['category'] : '-'); ?></strong></div>
                        <div class="settings-item"><span>起始日期</span><strong><?php echo e(!empty($lic['start_date']) ? $lic['start_date'] : '-'); ?></strong></div>
                        <div class="settings-item"><span>截止日期</span><strong style="<?php echo empty($lic['end_date']) ? 'color:#0369a1;' : ''; ?>"><?php echo e(license_end_date_display_text($lic)); ?></strong></div>
                        <?php if (!empty($lic['end_date']) && !$licExpired): ?>
                        <div class="settings-item"><span>剩余天数</span><strong><?php $d = license_days_remaining(); echo $d >= 0 ? $d . ' 天' : '-'; ?></strong></div>
                        <?php endif; ?>
                        <div class="settings-item"><span>激活时间</span><strong><?php echo !empty($lic['activated_at']) ? date('Y-m-d H:i:s', (int)$lic['activated_at']) : '-'; ?></strong></div>
                        <div class="settings-item"><span>上次验证</span><strong><?php echo !empty($lic['last_verify_at']) ? date('Y-m-d H:i:s', (int)$lic['last_verify_at']) : '-'; ?></strong></div>
                    </div>
                    <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:20px;">
                        <form method="post" action="/admin/settings/index.php?tab=license">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="action" value="license_action">
                            <input type="hidden" name="op" value="verify">
                            <button class="btn-primary" type="submit">重新验证</button>
                        </form>
                        <form method="post" action="/admin/settings/index.php?tab=license" onsubmit="return confirm('确定要清除本地授权信息吗？清除后需重新激活才能使用后台。');">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="action" value="license_action">
                            <input type="hidden" name="op" value="deactivate">
                            <button class="btn-ghost" type="submit" style="color:#dc2626;">清除授权</button>
                        </form>
                        <a class="btn-soft" href="/activate.php">前往激活页</a>
                    </div>
                    <?php else: ?>
                    <div style="text-align:center;padding:32px 0;">
                        <p style="font-size:16px;color:#dc2626;font-weight:600;">系统尚未激活</p>
                        <p style="font-size:14px;color:#6b7280;margin:8px 0 20px;">请输入激活码以启用全部功能。</p>
                        <a class="btn-primary" href="/activate.php" style="display:inline-block;padding:10px 28px;text-decoration:none;">前往激活</a>
                    </div>
                    <?php endif; ?>
                </section>

                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>授权说明</h2><p>授权机制与注意事项。</p></div></div>
                    <div style="font-size:13px;color:#64748b;line-height:2;">
                        <p>• 系统安装后需激活才能使用后台功能，激活码由超级管理员发放。</p>
                        <p>• 激活后系统每 1 小时自动向授权服务器验证一次，验证失败将限制后台访问。</p>
                        <p>• 若授权服务器暂时不可达，系统提供 3 天宽限期，期间可正常使用。</p>
                        <p>• 授权绑定当前域名，更换域名需重新激活或联系管理员。</p>
                    </div>
                </section>
            <?php endif; ?>


            <?php if ($tab === 'maintenance'): ?>
                <section class="page-card settings-card">
                    <div class="card-head"><div><h2>维护操作</h2><p>常用的运维与安全操作入口，后续将逐步补充执行能力。</p></div></div>
                    <div class="settings-action-grid">
                        <div class="settings-action">
                            <strong>数据备份</strong>
                            <p>手动导出数据库与配置，用于版本升级或迁移前的回滚保障。</p>
                            <button class="btn-ghost" type="button" disabled>即将开放</button>
                        </div>
                        <div class="settings-action">
                            <strong>缓存清理</strong>
                            <p>清除模板、页面与静态发布缓存，发布新模板后推荐执行。</p>
                            <button class="btn-ghost" type="button" disabled>即将开放</button>
                        </div>
                        <div class="settings-action">
                            <strong>系统日志</strong>
                            <p>查看调度与发布日志，排查异常任务。</p>
                            <button class="btn-ghost" type="button" disabled>即将开放</button>
                        </div>
                        <div class="settings-action">
                            <strong>账号安全</strong>
                            <p>修改登录密码、查看登录记录。</p>
                            <a class="btn-ghost" href="admin-users.php">前往账户管理</a>
                        </div>
                    </div>
                </section>
            <?php endif; ?>

        </div>
    </main>
</div>
<script>
(function () {
    var strat = document.getElementById('friendStrategy');
    var wrap = document.getElementById('friendIncludeWrap');
    var exWrap = document.getElementById('friendExcludeWrap');
    if (strat) {
        strat.addEventListener('change', function () {
            if (wrap) wrap.style.display = strat.value === 'specified' ? '' : 'none';
            if (exWrap) exWrap.style.display = strat.value === 'blacklist' ? '' : 'none';
        });
    }
    var copyBtn = document.getElementById('btnCopyToken');
    var tokenInput = document.getElementById('schedulerToken');
    if (copyBtn && tokenInput) {
        copyBtn.addEventListener('click', function () {
            if (!tokenInput.value) return;
            if (navigator.clipboard) {
                navigator.clipboard.writeText(tokenInput.value).then(function () {
                    copyBtn.textContent = '已复制';
                    setTimeout(function () { copyBtn.textContent = '复制'; }, 1500);
                });
            } else {
                tokenInput.select();
                document.execCommand('copy');
                copyBtn.textContent = '已复制';
                setTimeout(function () { copyBtn.textContent = '复制'; }, 1500);
            }
        });
    }
    var addBtn = document.getElementById('friendAddRow');
    var list = document.getElementById('friendCustomWrap');
    function createLinkRow(name, url) {
        var row = document.createElement('div');
        row.className = 'friend-custom-row';
        row.style.display = 'grid';
        row.style.gridTemplateColumns = 'auto minmax(140px,1fr) minmax(260px,2.4fr) auto';
        row.style.gap = '8px';
        row.style.width = '100%';
        row.style.alignItems = 'center';
        row.innerHTML = '<input type="checkbox" class="friend-check" style="width:16px;height:16px;cursor:pointer;"><input class="input" type="text" name="friend_link_name[]" placeholder="链接名称，如：百度" value="' + (name || '').replace(/"/g, '&quot;') + '"><input class="input" type="text" name="friend_link_url[]" placeholder="https://example.com" value="' + (url || '').replace(/"/g, '&quot;') + '"><button class="btn-ghost friend-custom-remove" type="button">移除</button>';
        return row;
    }
    if (addBtn && list) {
        addBtn.addEventListener('click', function () {
            list.appendChild(createLinkRow('', ''));
        });
        list.addEventListener('click', function (e) {
            if (e.target && e.target.classList.contains('friend-custom-remove')) {
                var row = e.target.closest('.friend-custom-row');
                if (row && list.querySelectorAll('.friend-custom-row').length > 1) {
                    row.parentNode.removeChild(row);
                } else if (row) {
                    row.querySelectorAll('input').forEach(function (i) { i.value = ''; });
                }
            }
        });
    }
    var batchBtn = document.getElementById('friendBatchBtn');
    var batchPanel = document.getElementById('friendBatchPanel');
    var batchText = document.getElementById('friendBatchText');
    var batchConfirm = document.getElementById('friendBatchConfirm');
    var batchCancel = document.getElementById('friendBatchCancel');
    if (batchBtn && batchPanel && list) {
        batchBtn.addEventListener('click', function () {
            batchPanel.style.display = batchPanel.style.display === 'none' ? '' : 'none';
            if (batchPanel.style.display !== 'none') batchText.focus();
        });
        batchCancel.addEventListener('click', function () {
            batchPanel.style.display = 'none';
            batchText.value = '';
        });
        batchConfirm.addEventListener('click', function () {
            var lines = batchText.value.split('\n');
            var added = 0;
            for (var i = 0; i < lines.length; i++) {
                var line = lines[i].trim();
                if (!line) continue;
                var parts = line.split(/[\s\t]+/);
                if (parts.length < 2) continue;
                var url = parts[parts.length - 1];
                var name = parts.slice(0, parts.length - 1).join(' ');
                if (!name || !url) continue;
                /* Remove first empty row if exists */
                if (added === 0) {
                    var rows = list.querySelectorAll('.friend-custom-row');
                    if (rows.length === 1) {
                        var inputs = rows[0].querySelectorAll('input');
                        if (inputs[0].value === '' && inputs[1].value === '') {
                            rows[0].parentNode.removeChild(rows[0]);
                        }
                    }
                }
                list.appendChild(createLinkRow(name, url));
                added++;
            }
            batchText.value = '';
            batchPanel.style.display = 'none';
            if (added > 0) {
                batchBtn.textContent = '已导入 ' + added + ' 条';
                setTimeout(function () { batchBtn.textContent = '批量添加'; }, 2000);
            }
        });
    }
    // ===== 站点互链批量删除 =====
    var friendBatchDel = document.getElementById('friendBatchDelete');
    var friendCheckAll = document.getElementById('friendCheckAll');
    if (list && friendBatchDel) {
        function updateFriendBatchUI() {
            var checks = list.querySelectorAll('.friend-check:checked');
            friendBatchDel.style.display = checks.length > 0 ? '' : 'none';
        }
        list.addEventListener('change', function(e) {
            if (e.target.classList.contains('friend-check')) updateFriendBatchUI();
        });
        if (friendCheckAll) {
            friendCheckAll.addEventListener('change', function() {
                var all = list.querySelectorAll('.friend-check');
                for (var i = 0; i < all.length; i++) all[i].checked = friendCheckAll.checked;
                updateFriendBatchUI();
            });
        }
        friendBatchDel.addEventListener('click', function() {
            var checked = list.querySelectorAll('.friend-check:checked');
            if (!checked.length) return;
            if (!confirm('确定删除选中的 ' + checked.length + ' 条外链？')) return;
            for (var i = 0; i < checked.length; i++) {
                var row = checked[i].closest('.friend-custom-row');
                if (row) row.parentNode.removeChild(row);
            }
            if (list.querySelectorAll('.friend-custom-row').length === 0) {
                list.appendChild(createLinkRow('', ''));
            }
            friendCheckAll.checked = false;
            updateFriendBatchUI();
        });
    }

    // ===== 内链批量删除 =====
    var ilCheckAll = document.getElementById('ilCheckAll');
    var ilBatchDeleteBtn = document.getElementById('ilBatchDeleteBtn');
    var ilBatchIdsWrap = document.getElementById('ilBatchIdsWrap');
    var ilSelectedCount = document.getElementById('ilSelectedCount');
    function updateIlBatchUI() {
        var checks = document.querySelectorAll('.il-check:checked');
        if (ilBatchDeleteBtn) ilBatchDeleteBtn.style.display = checks.length > 0 ? '' : 'none';
        if (ilSelectedCount) ilSelectedCount.textContent = checks.length > 0 ? '已选 ' + checks.length + ' 项' : '';
        if (ilBatchIdsWrap) {
            ilBatchIdsWrap.innerHTML = '';
            for (var i = 0; i < checks.length; i++) {
                var h = document.createElement('input');
                h.type = 'hidden'; h.name = 'il_ids[]'; h.value = checks[i].value;
                ilBatchIdsWrap.appendChild(h);
            }
        }
    }
    if (ilCheckAll) {
        ilCheckAll.addEventListener('change', function() {
            var all = document.querySelectorAll('.il-check');
            for (var i = 0; i < all.length; i++) all[i].checked = ilCheckAll.checked;
            updateIlBatchUI();
        });
    }
    document.querySelectorAll('.il-check').forEach(function(cb) {
        cb.addEventListener('change', updateIlBatchUI);
    });

    // ===== 内链关键词编辑 =====
    var ilForm = document.getElementById('ilKeywordForm');
    var ilEditId = document.getElementById('ilEditId');
    var ilKeyword = document.getElementById('ilKeyword');
    var ilUrl = document.getElementById('ilUrl');
    var ilMode = document.getElementById('ilMode');
    var ilMaxReplace = document.getElementById('ilMaxReplace');
    var ilPriority = document.getElementById('ilPriority');
    var ilStatus = document.getElementById('ilStatus');
    var ilSubmitBtn = document.getElementById('ilSubmitBtn');
    var ilCancelBtn = document.getElementById('ilCancelBtn');

    if (ilForm) {
        document.querySelectorAll('.il-edit-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var tr = btn.closest('tr');
                if (!tr) return;
                ilEditId.value = tr.dataset.id || '0';
                ilKeyword.value = tr.dataset.keyword || '';
                ilUrl.value = tr.dataset.url || '';
                ilMode.value = tr.dataset.mode || 'match';
                ilMaxReplace.value = tr.dataset.max || '1';
                ilPriority.value = tr.dataset.priority || '0';
                ilStatus.checked = tr.dataset.status === '1';
                ilSubmitBtn.textContent = '更新';
                ilCancelBtn.style.display = '';
                ilKeyword.focus();
            });
        });

        if (ilCancelBtn) {
            ilCancelBtn.addEventListener('click', function () {
                ilEditId.value = '0';
                ilKeyword.value = '';
                ilUrl.value = '';
                ilMode.value = 'match';
                ilMaxReplace.value = '1';
                ilPriority.value = '0';
                ilStatus.checked = true;
                ilSubmitBtn.textContent = '添加';
                ilCancelBtn.style.display = 'none';
            });
        }
    }

    // ===== 内链预览 =====
    var previewBtn = document.getElementById('ilPreviewBtn');
    var previewInput = document.getElementById('ilPreviewInput');
    var previewResult = document.getElementById('ilPreviewResult');
    if (previewBtn && previewInput && previewResult) {
        previewBtn.addEventListener('click', function () {
            var text = previewInput.value.trim();
            if (!text) { previewResult.style.display = 'none'; return; }
            // 从表格收集当前关键词数据
            var links = [];
            document.querySelectorAll('#ilKeywordForm ~ div table tbody tr, .page-card table tbody tr').forEach(function (tr) {
                if (!tr.dataset.keyword) return;
                if (tr.dataset.status !== '1') return;
                links.push({
                    keyword: tr.dataset.keyword,
                    url: tr.dataset.url,
                    mode: tr.dataset.mode,
                    max: parseInt(tr.dataset.max) || 1
                });
            });
            if (!links.length) {
                previewResult.innerHTML = '<span style="color:#94a3b8;">暂无已启用的关键词链接规则。</span>';
                previewResult.style.display = '';
                return;
            }
            // 简易客户端替换预览
            var html = '<p>' + text.replace(/\n/g, '</p><p>') + '</p>';
            var matchLinks = links.filter(function (l) { return l.mode === 'match'; });
            var forceLinks = links.filter(function (l) { return l.mode === 'force'; });
            matchLinks.sort(function (a, b) { return b.keyword.length - a.keyword.length; });
            matchLinks.forEach(function (l) {
                var esc = l.keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                var re = new RegExp('(?![^<]*>)(' + esc + ')', 'gi');
                var count = 0, max = l.max || 999;
                html = html.replace(re, function (m) {
                    if (count >= max) return m;
                    count++;
                    return '<a href="' + l.url + '" style="color:#6366f1;text-decoration:underline;">' + m + '</a>';
                });
            });
            if (forceLinks.length) {
                var pTags = [];
                html.replace(/<\/p>/gi, function(m, offset) { pTags.push(offset); return m; });
                if (pTags.length) {
                    var insertions = {};
                    forceLinks.forEach(function (l, i) {
                        var posIdx = Math.floor(i * pTags.length / forceLinks.length) % pTags.length;
                        var anchor = ' <a href="' + l.url + '" style="color:#f59e0b;text-decoration:underline;">' + l.keyword + '</a>';
                        if (!insertions[posIdx]) insertions[posIdx] = '';
                        insertions[posIdx] += anchor;
                    });
                    var keys = Object.keys(insertions).map(Number).sort(function(a,b){return b-a;});
                    keys.forEach(function(pi) {
                        var off = pTags[pi];
                        html = html.substring(0, off) + insertions[pi] + html.substring(off);
                    });
                }
            }
            previewResult.innerHTML = '<div style="margin-bottom:8px;font-weight:600;color:#475569;font-size:12px;">处理后预览（蓝色=匹配替换，橙色=强制插入）：</div>' + html;
            previewResult.style.display = '';
        });
    }
})();
</script>
<script src="/assets/js/admin-ui.js"></script>
</body>
</html>
