{include file="app/manage/view/index/emlog_nav"}

<h1 class="page-title">
    <i class="fas fa-cogs"></i>
    系统设置
</h1>

<div class="row">
    <div class="col-lg-12">
        <!-- 设置选项卡 -->
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="myTab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="basic-tab" data-toggle="tab" href="#basic" role="tab" aria-controls="basic" aria-selected="true">
                            <i class="fas fa-home"></i> 基础设置
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="url-tab" data-toggle="tab" href="#url" role="tab" aria-controls="url" aria-selected="false">
                            <i class="fas fa-link"></i> URL设置
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="seo-tab" data-toggle="tab" href="#seo" role="tab" aria-controls="seo" aria-selected="false">
                            <i class="fas fa-search"></i> SEO设置
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="seopush-tab" data-toggle="tab" href="#seopush" role="tab" aria-controls="seopush" aria-selected="false">
                            <i class="fas fa-rocket"></i> SEO推送
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="interact-tab" data-toggle="tab" href="#interact" role="tab" aria-controls="interact" aria-selected="false">
                            <i class="fas fa-comments"></i> 互动设置
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="aichat-tab" data-toggle="tab" href="#aichat" role="tab" aria-controls="aichat" aria-selected="false">
                            <i class="fas fa-robot"></i> AI对话
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="tplengine-tab" data-toggle="tab" href="#tplengine" role="tab" aria-controls="tplengine" aria-selected="false">
                            <i class="fas fa-layer-group"></i> 模板引擎
                        </a>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content" id="myTabContent">
                    <!-- 基础设置 -->
                    <div class="tab-pane fade show active" id="basic" role="tabpanel" aria-labelledby="basic-tab">
                        <form id="index-form">
                            <!-- 站点信息 -->
                            <h5 class="section-title"><i class="fas fa-info-circle"></i> 站点信息</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="sitename" class="font-weight-bold">网站名称 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="sitename" name="sitename" placeholder="请输入网站名称" value="<?php echo isset($ret['sitename']) ? $ret['sitename'] : ''; ?>">
                                        <small class="form-text text-muted">显示在网站标题和页面顶部</small>
                                    </div>
                                    <div class="form-group">
                                        <label for="hosturl" class="font-weight-bold">网站地址 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="hosturl" name="hosturl" placeholder="例如: http://www.example.com" value="<?php echo isset($ret['hosturl']) ? $ret['hosturl'] : ''; ?>">
                                        <small class="form-text text-muted">网站完整地址，用于SEO优化</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="beian" class="font-weight-bold">备案号</label>
                                        <input type="text" class="form-control" id="beian" name="beian" placeholder="备案号" value="<?php echo isset($ret['beian']) ? $ret['beian'] : ''; ?>">
                                        <small class="form-text text-muted">工信部备案号，显示在页面底部</small>
                                    </div>
                                    <div class="form-group">
                                        <label for="sitekeywords" class="font-weight-bold">网站关键词</label>
                                        <input type="text" class="form-control" id="sitekeywords" name="sitekeywords" placeholder="请输入网站关键词" value="<?php echo isset($ret['sitekeywords']) ? $ret['sitekeywords'] : ''; ?>">
                                        <small class="form-text text-muted">多个关键词用逗号分隔</small>
                                    </div>
                                </div>
                            </div>

                            <!-- 主页展示（模板化插件主页） -->
                            <h5 class="section-title"><i class="fas fa-tv"></i> 主页展示</h5>
                            <div class="form-group">
                                <label for="home_plug" class="font-weight-bold">主页展示插件</label>
                                <select class="form-control" id="home_plug" name="home_plug">
                                    <option value="">不使用插件主页（默认站点首页）</option>
                                    <?php if (!empty($homePlugins)): foreach ($homePlugins as $hp): ?>
                                    <option value="<?php echo $hp['alias']; ?>" <?php echo (isset($homePlug) && $homePlug === $hp['alias']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($hp['name']); ?>（<?php echo $hp['alias']; ?>）
                                    </option>
                                    <?php endforeach; endif; ?>
                                </select>
                                <small class="form-text text-muted">选择后，访问网站根域名将直接展示该插件模板（仅模板化插件可选）。设为“不使用插件主页”即恢复默认站点首页。</small>
                            </div>

                            <!-- 后台访问锁（防爆破/隐藏真实后台入口） -->
                            <h5 class="section-title"><i class="fas fa-lock"></i> 后台访问锁</h5>
                            <div class="form-group">
                                <label for="manage_gate_key" class="font-weight-bold">安全参数名</label>
                                <input type="text" class="form-control" id="manage_gate_key" name="manage_gate_key" placeholder="例如: zhicms" value="<?php echo isset($ret['manage_gate_key']) ? htmlspecialchars($ret['manage_gate_key'], ENT_QUOTES) : ''; ?>">
                                <small class="form-text text-muted">后台入口 GET 参数名。设置后，访问后台必须带此参数（如 <code>?zhicms=xxx</code>），否则跳转到首页。留空则关闭此锁（首次安装默认关闭）。</small>
                            </div>
                            <div class="form-group">
                                <label for="manage_gate_val" class="font-weight-bold">安全参数值</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="manage_gate_val" name="manage_gate_val" placeholder="例如: admin" value="<?php echo isset($ret['manage_gate_val']) ? htmlspecialchars($ret['manage_gate_val'], ENT_QUOTES) : ''; ?>">
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary" type="button" onclick="document.getElementById('manage_gate_val').value = Math.random().toString(36).slice(2,10) + Math.random().toString(36).slice(2,10);">随机生成</button>
                                    </div>
                                </div>
                                <small class="form-text text-muted">后台入口 GET 参数值。建议设置足够长的随机串（如 16 位）。示例后台地址：<code>index.php?r=manage/login/index&amp;<?php echo isset($ret['manage_gate_key']) ? htmlspecialchars($ret['manage_gate_key'], ENT_QUOTES) : 'zhicms'; ?>=你的参数值</code>。请务必牢记，遗忘需手动改数据库恢复。</small>
                            </div>

                            <!-- 站点状态（关闭站点 + 关闭说明 放在一起） -->
                            <h5 class="section-title"><i class="fas fa-power-off"></i> 站点状态</h5>
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="closed" name="closed" value="1" <?php echo isset($ret['closed']) && $ret['closed'] == '1' ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="closed">关闭站点</label>
                                </div>
                                <small class="form-text text-muted">开启后前台访客将无法访问网站（后台不受影响）</small>
                            </div>
                            <div class="form-group">
                                <label for="closemsg" class="font-weight-bold">关闭提示</label>
                                <textarea class="form-control" id="closemsg" name="closemsg" rows="2" placeholder="站点关闭时显示的提示信息"><?php echo isset($ret['closemsg']) ? $ret['closemsg'] : ''; ?></textarea>
                            </div>

                            <!-- 内容与版权 -->
                            <h5 class="section-title"><i class="fas fa-font"></i> 内容与版权</h5>
                            <div class="form-group">
                                <label for="sitedescription" class="font-weight-bold">网站描述</label>
                                <textarea class="form-control" id="sitedescription" name="sitedescription" rows="3" placeholder="请输入网站描述"><?php echo isset($ret['sitedescription']) ? $ret['sitedescription'] : ''; ?></textarea>
                                <small class="form-text text-muted">网站简介，用于SEO优化</small>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="about" class="font-weight-bold">关于我们</label>
                                        <textarea class="form-control" id="about" name="about" rows="4" placeholder="关于我们"><?php echo isset($ret['about']) ? $ret['about'] : ''; ?></textarea>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="banquan" class="font-weight-bold">底部版权</label>
                                        <input type="text" class="form-control" id="banquan" name="banquan" placeholder="网站底部版权" value="<?php echo isset($ret['banquan']) ? $ret['banquan'] : ''; ?>">
                                        <small class="form-text text-muted">页脚显示的版权信息</small>
                                    </div>
                                </div>
                            </div>

                            <!-- 媒体与形象 -->
                            <h5 class="section-title"><i class="fas fa-image"></i> 媒体与形象</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">网站LOGO</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="logo-input" name="logo" placeholder="请输入LOGO图片地址" value="<?php echo isset($ret['logo']) ? $ret['logo'] : ''; ?>">
                                            <div class="input-group-append">
                                                <button type="button" class="btn btn-outline-secondary" onclick="uploadImage('logo')">
                                                    <i class="fas fa-upload"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <?php if (isset($ret['logo']) && $ret['logo']): ?>
                                        <div class="mt-2">
                                            <img src="<?php echo $ret['logo']; ?>" class="img-thumbnail mw-120" style="max-height: 60px">
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">二维码</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="ewm-input" name="ewm" placeholder="请输入二维码图片地址" value="<?php echo isset($ret['ewm']) ? $ret['ewm'] : ''; ?>">
                                            <div class="input-group-append">
                                                <button type="button" class="btn btn-outline-secondary" onclick="uploadImage('ewm')">
                                                    <i class="fas fa-upload"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <?php if (isset($ret['ewm']) && $ret['ewm']): ?>
                                        <div class="mt-2">
                                            <img src="<?php echo $ret['ewm']; ?>" class="img-thumbnail mw-100" style="max-height: 100px">
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="font-weight-bold">默认图片</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="defaultimg-input" name="defaultimg" placeholder="请输入默认图片地址" value="<?php echo isset($ret['defaultimg']) ? $ret['defaultimg'] : ''; ?>">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-outline-secondary" onclick="uploadImage('defaultimg')">
                                            <i class="fas fa-upload"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- 图片与水印 -->
                            <h5 class="section-title"><i class="fas fa-tint"></i> 图片与水印</h5>
                            <div class="form-group">
                                <label class="font-weight-bold">图片水印设置</label>
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="watermark" name="watermark" value="1" <?php echo isset($ret['watermark']) && $ret['watermark'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="watermark">开启水印</label>
                                        </div>
                                    </div>
                                    <div class="col-md-8">
                                        <input type="text" class="form-control" id="watermarktext" name="watermarktext" placeholder="水印文字" value="<?php echo isset($ret['watermarktext']) ? $ret['watermarktext'] : ''; ?>">
                                    </div>
                                </div>
                                <small class="form-text text-muted">为上传的图片添加文字水印</small>
                            </div>
                            <div class="form-group">
                                <label for="cdnurl" class="font-weight-bold">CDN设置</label>
                                <input type="text" class="form-control" id="cdnurl" name="cdnurl" placeholder="图片/附件独立域名，如 http://cdn.example.com" value="<?php echo isset($ret['cdnurl']) ? $ret['cdnurl'] : ''; ?>">
                                <small class="form-text text-muted">留空则使用网站域名，需将域名指向 uploadfile 目录</small>
                            </div>

                            <!-- 功能与性能 -->
                            <h5 class="section-title"><i class="fas fa-cogs"></i> 功能与性能</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="download" class="font-weight-bold">下载链接</label>
                                        <input type="text" class="form-control" id="download" name="download" placeholder="客户端下载地址" value="<?php echo isset($ret['download']) ? $ret['download'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="cachetime" class="font-weight-bold">缓存时间（秒）</label>
                                        <input type="number" class="form-control" id="cachetime" name="cachetime" placeholder="3600" value="<?php echo isset($ret['cachetime']) ? $ret['cachetime'] : '3600'; ?>">
                                        <small class="form-text text-muted">设置页面缓存有效时间</small>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="pagelimit" class="font-weight-bold">分页条数</label>
                                <input type="number" class="form-control" id="pagelimit" name="pagelimit" placeholder="20" value="<?php echo isset($ret['pagelimit']) ? $ret['pagelimit'] : '20'; ?>">
                                <small class="form-text text-muted">每页显示的项目数量</small>
                            </div>

                            <!-- 安全 Key（统一接口密钥） -->
                            <h5 class="section-title"><i class="fas fa-key"></i> 安全 Key</h5>
                            <div class="form-group">
                                <label class="font-weight-bold">接口安全 Key</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="security_key" name="security_key" readonly
                                           value="<?php echo isset($securityKey) ? htmlspecialchars($securityKey, ENT_QUOTES, 'UTF-8') : ''; ?>"
                                           style="font-family:monospace;letter-spacing:.5px">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-outline-warning" onclick="resetSecurityKey()">
                                            <i class="fas fa-sync-alt"></i> 重置
                                        </button>
                                    </div>
                                </div>
                                <small class="form-text text-muted">
                                    用于外部接口鉴权（自动生成，可点击「重置」重新生成）。<br>
                                    · <b>火车头/简数采集器免登</b>：<code>?r=index/import/insertData&amp;pw=安全Key</code>、<code>?r=index/import/index&amp;key=安全Key</code><br>
                                    · <b>在线升级</b>：单文件 install.php 升级时输入此 Key<br>
                                    · <b>小程序/App API</b>：接口 Token 签名密钥
                                </small>
                            </div>

                            <div class="form-group border-top pt-3 mt-4">
                                <button type="button" class="btn btn-primary btn-lg px-5" onclick="submitForm('index')">
                                    <i class="fas fa-save"></i> 保存设置
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- URL设置 -->
                    <div class="tab-pane fade" id="url" role="tabpanel" aria-labelledby="url-tab">
                        <form id="url-form" class="mt-4">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">网站模式</label>
                                        <select class="custom-select" id="DEBUG" name="DEBUG">
                                            <option value="0" <?php echo !isset($DEBUG) || $DEBUG == 0 ? 'selected' : ''; ?>>安全模式</option>
                                            <option value="1" <?php echo isset($DEBUG) && $DEBUG == 1 ? 'selected' : ''; ?>>调试模式</option>
                                        </select>
                                        <small class="form-text text-muted">调试模式会显示错误信息</small>
                                    </div>

                                    <div class="form-group">
                                        <label class="font-weight-bold">首页默认访问</label>
                                        <select class="custom-select" id="moren" name="moren">
                                            <option value="index" <?php echo isset($moren) && $moren == 'index' ? 'selected' : ''; ?>>国内折扣</option>
                                            <option value="haitao" <?php echo isset($moren) && $moren == 'haitao' ? 'selected' : ''; ?>>海淘折扣</option>
                                            <option value="cheaps" <?php echo isset($moren) && $moren == 'cheaps' ? 'selected' : ''; ?>>优惠券</option>
                                            <option value="rank" <?php echo isset($moren) && $moren == 'rank' ? 'selected' : ''; ?>>排行榜</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="font-weight-bold">伪静态设置</label>
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="REWRITE_ON" name="REWRITE_ON" value="1" <?php echo isset($REWRITE_ON) && $REWRITE_ON == 1 ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="REWRITE_ON">开启伪静态</label>
                                        </div>
                                        <small class="form-text text-muted">需要配置网站服务器支持</small>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group border-top pt-3 mt-4">
                                <button type="button" class="btn btn-primary btn-lg px-5" onclick="submitForm('url')">
                                    <i class="fas fa-save"></i> 保存设置
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- SEO设置 -->
                    <div class="tab-pane fade" id="seo" role="tabpanel" aria-labelledby="seo-tab">
                        <form id="seo-form" class="mt-4">
                            <h5 class="sub-title mb-4">首页SEO</h5>
                            <div class="form-group">
                                <label for="index_title" class="font-weight-bold">网站首页标题</label>
                                <input type="text" class="form-control" id="index_title" name="index_title" placeholder="网站首页标题" value="<?php echo isset($ret['index_title']) ? $ret['index_title'] : ''; ?>">
                                <small class="form-text text-muted">首页标题，用于SEO优化</small>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="index_keywords" class="font-weight-bold">网站首页关键字</label>
                                        <input type="text" class="form-control" id="index_keywords" name="index_keywords" placeholder="网站首页关键字" value="<?php echo isset($ret['index_keywords']) ? $ret['index_keywords'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="index_dec" class="font-weight-bold">网站首页描述</label>
                                        <input type="text" class="form-control" id="index_dec" name="index_dec" placeholder="网站首页描述" value="<?php echo isset($ret['index_dec']) ? $ret['index_dec'] : ''; ?>">
                                    </div>
                                </div>
                            </div>

                            <h5 class="sub-title mb-4 mt-5">大牌风尚SEO</h5>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="brand_title" class="font-weight-bold">大牌风尚标题</label>
                                        <input type="text" class="form-control" id="brand_title" name="brand_title" placeholder="大牌风尚标题" value="<?php echo isset($ret['brand_title']) ? $ret['brand_title'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="brand_keywords" class="font-weight-bold">大牌风尚关键词</label>
                                        <input type="text" class="form-control" id="brand_keywords" name="brand_keywords" placeholder="大牌风尚关键词" value="<?php echo isset($ret['brand_keywords']) ? $ret['brand_keywords'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="brand_dec" class="font-weight-bold">大牌风尚描述</label>
                                        <input type="text" class="form-control" id="brand_dec" name="brand_dec" placeholder="大牌风尚页面描述" value="<?php echo isset($ret['brand_dec']) ? $ret['brand_dec'] : ''; ?>">
                                    </div>
                                </div>
                            </div>

                            <h5 class="sub-title mb-4 mt-5">风云榜SEO</h5>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="rank_title" class="font-weight-bold">风云榜标题</label>
                                        <input type="text" class="form-control" id="rank_title" name="rank_title" placeholder="风云榜标题" value="<?php echo isset($ret['rank_title']) ? $ret['rank_title'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="rank_keywords" class="font-weight-bold">风云榜关键词</label>
                                        <input type="text" class="form-control" id="rank_keywords" name="rank_keywords" placeholder="风云榜关键词" value="<?php echo isset($ret['rank_keywords']) ? $ret['rank_keywords'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="rank_dec" class="font-weight-bold">风云榜描述</label>
                                        <input type="text" class="form-control" id="rank_dec" name="rank_dec" placeholder="风云榜描述" value="<?php echo isset($ret['rank_dec']) ? $ret['rank_dec'] : ''; ?>">
                                    </div>
                                </div>
                            </div>

                            <h5 class="sub-title mb-4 mt-5">优惠券SEO</h5>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="cheaps_title" class="font-weight-bold">优惠券标题</label>
                                        <input type="text" class="form-control" id="cheaps_title" name="cheaps_title" placeholder="优惠券标题" value="<?php echo isset($ret['cheaps_title']) ? $ret['cheaps_title'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="cheaps_keywords" class="font-weight-bold">优惠券关键词</label>
                                        <input type="text" class="form-control" id="cheaps_keywords" name="cheaps_keywords" placeholder="优惠券关键词" value="<?php echo isset($ret['cheaps_keywords']) ? $ret['cheaps_keywords'] : ''; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="cheaps_dec" class="font-weight-bold">优惠券描述</label>
                                        <input type="text" class="form-control" id="cheaps_dec" name="cheaps_dec" placeholder="优惠券描述" value="<?php echo isset($ret['cheaps_dec']) ? $ret['cheaps_dec'] : ''; ?>">
                                    </div>
                                </div>
                            </div>

                            <div class="form-group border-top pt-3 mt-5">
                                <button type="button" class="btn btn-primary btn-lg px-5" onclick="submitForm('seo')">
                                    <i class="fas fa-save"></i> 保存设置
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- SEO推送 -->
                    <div class="tab-pane fade" id="seopush" role="tabpanel" aria-labelledby="seopush-tab">
                        <form id="seopush-form" class="mt-4">
                            <!-- 百度站长平台 -->
                            <h5 class="sub-title mb-4">
                                <i class="fas fa-paw" style="color:#3385ff;"></i> 百度站长平台
                                <small class="text-muted ml-2">提高百度收录 80% 的必经之路</small>
                            </h5>
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label class="font-weight-bold">推送 Token</label>
                                        <input type="text" class="form-control" name="baidu_token" placeholder="百度站长平台 → 普通收录 → 接口调用地址中的 token 参数" value="<?php echo isset($ret['baidu_token']) ? $ret['baidu_token'] : ''; ?>">
                                        <small class="form-text text-muted">
                                            获取方式：<a href="https://ziyuan.baidu.com/linksubmit/" target="_blank">百度站长平台</a> → 普通收录 → 推送接口
                                        </small>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="font-weight-bold">状态</label>
                                        <div class="custom-control custom-switch mt-2">
                                            <input type="checkbox" class="custom-control-input" id="baidu_enabled" name="baidu_enabled" value="1" <?php echo isset($ret['baidu_enabled']) && $ret['baidu_enabled']=='1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="baidu_enabled">启用百度推送</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Bing Webmaster -->
                            <h5 class="sub-title mb-4 mt-5">
                                <i class="fas fa-globe" style="color:#00897b;"></i> Bing Webmaster
                                <small class="text-muted ml-2">覆盖必应、Yahoo、DuckDuckGo 等搜索引擎</small>
                            </h5>
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label class="font-weight-bold">API Key</label>
                                        <input type="text" class="form-control" name="bing_apikey" placeholder="Bing Webmaster → API 访问 → API 密钥" value="<?php echo isset($ret['bing_apikey']) ? $ret['bing_apikey'] : ''; ?>">
                                        <small class="form-text text-muted">
                                            获取方式：<a href="https://www.bing.com/webmasters/" target="_blank">Bing Webmaster</a> → 设置 → API 访问
                                        </small>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="font-weight-bold">状态</label>
                                        <div class="custom-control custom-switch mt-2">
                                            <input type="checkbox" class="custom-control-input" id="bing_enabled" name="bing_enabled" value="1" <?php echo isset($ret['bing_enabled']) && $ret['bing_enabled']=='1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="bing_enabled">启用 Bing 推送</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Sitemap & Ping -->
                            <h5 class="sub-title mb-4 mt-5">
                                <i class="fas fa-share-alt" style="color:#e0245e;"></i> Sitemap &amp; Ping
                                <small class="text-muted ml-2">生成 sitemap.xml + Ping 搜索引擎</small>
                            </h5>
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label class="font-weight-bold">Token（任意字符串即可启用）</label>
                                        <input type="text" class="form-control" name="weibo_token" placeholder="输入任意内容即启用 Sitemap 生成和 Ping 功能" value="<?php echo isset($ret['weibo_token']) ? $ret['weibo_token'] : ''; ?>">
                                        <small class="form-text text-muted">
                                            启用后将自动生成 <code>/sitemap.xml</code> 和 <code>/sitemap.txt</code>，并向百度/Google 发送 Ping
                                        </small>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="font-weight-bold">状态</label>
                                        <div class="custom-control custom-switch mt-2">
                                            <input type="checkbox" class="custom-control-input" id="weibo_enabled" name="weibo_enabled" value="1" <?php echo isset($ret['weibo_enabled']) && $ret['weibo_enabled']=='1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="weibo_enabled">启用 Sitemap</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 自动推送策略 -->
                            <h5 class="sub-title mb-4 mt-5">
                                <i class="fas fa-magic" style="color:#ff6b6b;"></i> 自动推送策略
                            </h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="auto_push" name="auto_push" value="1" <?php echo isset($ret['auto_push']) && $ret['auto_push']=='1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="auto_push">定时自动推送（每小时推送新文章）</label>
                                        </div>
                                        <small class="form-text text-muted">启用后系统会在后台定时将新文章推送到已启用的平台</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="push_on_save" name="push_on_save" value="1" <?php echo isset($ret['push_on_save']) && $ret['push_on_save']=='1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="push_on_save">发布时即时推送</label>
                                        </div>
                                        <small class="form-text text-muted">发布新文章时立刻推送到搜索引擎</small>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group border-top pt-3 mt-4">
                                <button type="button" class="btn btn-primary btn-lg px-5" onclick="submitForm('seopush')">
                                    <i class="fas fa-save"></i> 保存设置
                                </button>
                            </div>
                        </form>

                        <!-- 手动推送 -->
                        <h5 class="sub-title mb-4 mt-5"><i class="fas fa-paper-plane"></i> 手动推送</h5>
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group">
                                    <label class="font-weight-bold">推送 URL（每行一个，支持相对路径）</label>
                                    <textarea class="form-control" id="pushUrls" rows="6" placeholder="index.html
view-123.html
cheaps.html
https://www.example.com/brand.html"></textarea>
                                    <small class="form-text text-muted">
                                        将上述 URL 推送到百度、Bing 等已启用的搜索引擎平台
                                    </small>
                                </div>
                                <button type="button" class="btn btn-success mr-2" onclick="doPush2()">
                                    <i class="fas fa-rocket"></i> 开始推送
                                </button>
                                <button type="button" class="btn btn-outline-info mr-2" onclick="quickPush2('recent')">
                                    <i class="fas fa-clock"></i> 推送最新 50 篇
                                </button>
                                <button type="button" class="btn btn-outline-warning" onclick="quickPush2('all')">
                                    <i class="fas fa-globe"></i> 推送全站
                                </button>
                                <div id="push-result" class="mt-3 d-none"></div>
                            </div>
                            <div class="col-md-4">
                                <div class="alert alert-info">
                                    <h6><i class="fas fa-info-circle"></i> 推送说明</h6>
                                    <ul class="mb-0 pl-3 small">
                                        <li>百度每日限额 3000 条 URL</li>
                                        <li>Bing 每次最多 100 条</li>
                                        <li>重复推送不产生副作用</li>
                                        <li>推送后 24-48h 生效</li>
                                    </ul>
                                </div>
                            </div>
                        </div>

                        <!-- 推送日志 -->
                        <h5 class="sub-title mb-4 mt-4">
                            <i class="fas fa-history"></i> 推送日志（最近 20 条）
                            <button type="button" class="btn btn-sm btn-outline-danger float-right" onclick="clearLog2()">
                                <i class="fas fa-trash"></i> 清空日志
                            </button>
                        </h5>
                        <div style="max-height:400px;overflow-y:auto;">
                            <?php if (isset($pushLog) && !empty($pushLog)): ?>
                            <table class="table table-sm table-striped">
                                <thead><tr><th>时间</th><th>URL</th><th>数量</th><th>详情</th></tr></thead>
                                <tbody>
                                <?php foreach (array_slice($pushLog, 0, 20) as $log): ?>
                                <tr>
                                    <td class="text-nowrap small"><?php echo $log['time'] ?? ''; ?></td>
                                    <td class="small text-truncate mw-200"><?php echo isset($log['url']) ? $log['url'] : (isset($log['urls']) ? count($log['urls']).' 条URL' : ''); ?></td>
                                    <td class="small"><?php echo $log['total'] ?? 1; ?> 条</td>
                                    <td class="small">
                                        <?php
                                        if (isset($log['results'])):
                                            foreach ($log['results'] as $plat => $r):
                                                $icon = ['baidu'=>'&#x1F535;','bing'=>'&#x1F7E2;','weibo'=>'&#x1F534;'][$plat] ?? '&#x26AA;';
                                                $msg = isset($r['success']) ? '成功' . $r['success'] : (isset($r['code']) ? 'HTTP' . $r['code'] : '已推送');
                                                echo '<span class="badge badge-light mr-1">' . $icon . ' ' . $plat . ': ' . $msg . '</span>';
                                            endforeach;
                                        endif;
                                        ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                            <?php else: ?>
                            <p class="text-muted text-center py-4">暂无推送记录</p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- 互动设置 -->
                    <div class="tab-pane fade" id="interact" role="tabpanel" aria-labelledby="interact-tab">
                        <form id="interact-form" class="mt-4">
                            <h5 class="section-title"><i class="fas fa-toggle-on"></i> 功能总开关</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="comment_on" name="comment_on" value="1" <?php echo isset($ret['comment_on']) && $ret['comment_on'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="comment_on">开启评论功能</label>
                                        </div>
                                        <small class="form-text text-muted">关闭后前台文章详情页评论区将不显示，也无法提交评论</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="forum_on" name="forum_on" value="1" <?php echo isset($ret['forum_on']) && $ret['forum_on'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="forum_on">开启社区功能</label>
                                        </div>
                                        <small class="form-text text-muted">关闭后前台社区入口和页面将无法访问</small>
                                    </div>
                                </div>
                            </div>

                            <h5 class="section-title mt-4"><i class="fas fa-user-shield"></i> 评论规则</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="comment_anonymous" name="comment_anonymous" value="1" <?php echo isset($ret['comment_anonymous']) && $ret['comment_anonymous'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="comment_anonymous">允许未登录评论</label>
                                        </div>
                                        <small class="form-text text-muted">开启后未登录访客可通过"昵称+邮箱+cookie"提交评论</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="comment_check" name="comment_check" value="1" <?php echo isset($ret['comment_check']) && $ret['comment_check'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="comment_check">评论需要审核</label>
                                        </div>
                                        <small class="form-text text-muted">开启后新提交的评论默认隐藏，需在后台审核通过后显示</small>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="comment_interval" class="font-weight-bold">评论间隔（秒）</label>
                                <input type="number" class="form-control" id="comment_interval" name="comment_interval" min="0" max="3600" value="<?php echo isset($ret['comment_interval']) ? (int)$ret['comment_interval'] : 60; ?>">
                                <small class="form-text text-muted">同一 IP 在该秒数内无法再次评论，0 表示不限制（防刷建议 30~120 秒）</small>
                            </div>

                            <h5 class="section-title mt-4"><i class="fas fa-user-circle"></i> 用户注册设置</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="user_show_login" name="user_show_login" value="1" <?php echo isset($ret['user_show_login']) && $ret['user_show_login'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="user_show_login">前台显示登录/注册入口</label>
                                        </div>
                                        <small class="form-text text-muted">关闭后前台侧栏不再展示登录/注册按钮（已登录用户仍可见用户中心）</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="user_reg_captcha" name="user_reg_captcha" value="1" <?php echo isset($ret['user_reg_captcha']) && $ret['user_reg_captcha'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="user_reg_captcha">注册开启图形验证码</label>
                                        </div>
                                        <small class="form-text text-muted">开启后注册需填写图形验证码，防机器人刷注册</small>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="user_email_verify" name="user_email_verify" value="1" <?php echo isset($ret['user_email_verify']) && $ret['user_email_verify'] == '1' ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="user_email_verify">注册需要邮箱验证</label>
                                        </div>
                                        <small class="form-text text-muted">预留开关，开启后注册邮箱将作为必填项（当前未强制发验证邮件）</small>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group border-top pt-3 mt-4">
                                <button type="button" class="btn btn-primary btn-lg px-5" onclick="submitForm('interact')">
                                    <i class="fas fa-save"></i> 保存设置
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- AI对话设置 -->
                    <div class="tab-pane fade" id="aichat" role="tabpanel" aria-labelledby="aichat-tab">
                        <form id="aichat-form" class="mt-4">
                            <div class="alert alert-primary border-0">
                                <i class="fas fa-info-circle mr-1"></i>
                                网站前端的 AI 对话机器人（小淘）与后台 AI 助手<b>共用「AI 开放平台」的模型池</b>。请先在
                                <a href="index.php?r=manage/ai/setting" target="_blank" class="alert-link">AI 开放平台 → 模型管理</a>
                                中添加大模型（支持同平台添加多个），再在下方指定用于前端对话的模型即可。
                            </div>

                            <h5 class="section-title"><i class="fas fa-robot"></i> 前端对话模型</h5>
                            <div class="form-group">
                                <label for="front_chat_key" class="font-weight-bold">选择前端 AI 对话使用的模型</label>
                                <select class="custom-select" id="front_chat_key" name="front_chat_key">
                                    <option value="">— 未指定（前端对话将不可用）—</option>
                                    <?php if (!empty($aiChatModels)): ?>
                                    <?php foreach ($aiChatModels as $mKey => $mVal): ?>
                                    <option value="<?php echo $mKey; ?>" <?php echo $mKey === $aiChatKey ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($mVal['model'], ENT_QUOTES); ?>
                                        （<?php echo htmlspecialchars(parse_url($mVal['api_url'], PHP_URL_HOST), ENT_QUOTES); ?>）
                                    </option>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                <small class="form-text text-muted">该下拉来自「AI 开放平台」中类型为「文本对话」的模型；切换后前端机器人立即生效</small>
                            </div>

                            <h5 class="section-title mt-4"><i class="fas fa-window-restore"></i> 前端 AI 助手悬浮窗</h5>
                            <div class="form-group">
                                <label class="d-block font-weight-bold mb-2">右下角 AI 助手悬浮按钮</label>
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="widget_enabled" name="widget_enabled" value="1" <?php echo (!isset($ret['widget_enabled']) || $ret['widget_enabled']) ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="widget_enabled">在前端页面显示右下角 AI 助手悬浮窗（关闭后全站不显示）</label>
                                </div>
                                <small class="form-text text-muted">控制前台所有页面右下角的「AI 助手」悬浮入口；关闭后用户无法发起前端 AI 对话，但后台 AI 助手不受影响</small>
                            </div>

                            <div class="form-group border-top pt-3 mt-4">
                                <button type="button" class="btn btn-primary btn-lg px-5" onclick="submitForm('aichat')">
                                    <i class="fas fa-save"></i> 保存设置
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- 模板引擎 -->
                    <div class="tab-pane fade" id="tplengine" role="tabpanel" aria-labelledby="tplengine-tab">
                        <div class="mt-4">
                            <?php
                                $tplEngineShow = isset($tplEngine) ? $tplEngine : 'legacy';
                                $isLegacy = ($tplEngineShow === 'legacy');
                            ?>
                            <div class="alert <?php echo $isLegacy ? 'alert-primary' : 'alert-success'; ?> border-0 d-flex align-items-center">
                                <i class="fas fa-check-circle mr-2"></i>
                                <div>
                                    当前使用模板引擎：
                                    <strong class="h5 mb-0">
                                        <?php echo $isLegacy ? 'ZhiCms 自研引擎' : 'ThinkTemplate（真·ThinkPHP 引擎）'; ?>
                                    </strong>
                                </div>
                            </div>

                            <div class="alert alert-warning border-0">
                                <i class="fas fa-exclamation-triangle mr-1"></i>
                                <strong>请勿随意切换模板引擎！</strong>
                                当前主题的模板文件是按当前引擎的语法编写的。若随意切换到另一种引擎，<strong>前端页面很可能直接报错崩溃（空白页 / 语法错误 / 样式错乱）</strong>。
                                仅当您已按新引擎语法重写 <code>app/index/view/</code> 下所有模板，才建议切换。
                                切换后请务必清除模板编译缓存（系统 → 缓存管理 或删除 <code>data/cache/tpl*</code>），并逐个检查前端页面。
                            </div>

                            <div class="form-group">
                                <label for="tplEngine" class="font-weight-bold">切换模板引擎（仅供开发 / 已重写模板时使用）</label>
                                <select class="custom-select" id="tplEngine" name="engine">
                                    <option value="legacy" <?php echo $isLegacy ? 'selected' : ''; ?>>ZhiCms 自研引擎（原生 &#123;标签&#125; 语法）</option>
                                    <option value="think" <?php echo !$isLegacy ? 'selected' : ''; ?>>ThinkTemplate（真·ThinkPHP 引擎，支持 &#123;&#58;函数&#125; / 布局继承）</option>
                                </select>
                                <small class="form-text text-muted">
                                    Legacy：兼容历史模板，使用 <code>&#123;&#36;var&#125;</code> / <code>&#123;if&#125;</code> / <code>&#123;foreach&#125;</code> 原生标签；
                                    ThinkTemplate：与 ThinkPHP 模板语法一致，支持 <code>&#123;&#58;func()&#125;</code> / <code>&#123;include file=&#34;...&#34;&#125;</code> / 布局继承，输出默认原样（不转义）。
                                </small>
                            </div>
                            <div class="form-group border-top pt-3 mt-4">
                                <button type="button" class="btn btn-warning btn-lg px-5" onclick="saveEngine()">
                                    <i class="fas fa-exchange-alt"></i> 确认切换
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{include file="app/manage/view/index/emlog_footer"}

<input type="hidden" name="__hash__" id="hash_field" value="<?php echo isset($hash) ? $hash : ''; ?>">

<script>
function submitForm(type) {
    var form = document.getElementById(type + '-form');
    var data = {};
    var inputs = form.querySelectorAll('input, textarea, select');

    inputs.forEach(function(input) {
        if(input.type === 'checkbox') {
            data[input.name] = input.checked ? '1' : '0';
        } else {
            data[input.name] = input.value;
        }
    });

    // 添加hash字段
    if(document.getElementById('hash_field')) {
        data['hash'] = document.getElementById('hash_field').value;
    }

    var url = 'index.php?r=manage/set/' + type;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var result = JSON.parse(xhr.responseText);
                if (result.status === 'y') {
                    showToast(result.info, 'success');
                    // 保存成功后刷新页面，使后台开关状态与数据库完全一致
                    setTimeout(function(){ location.reload(); }, 800);
                } else {
                    showToast(result.info, 'danger');
                }
            } catch(e) {
                showToast('数据保存失败', 'danger');
            }
        }
    };

    var params = Object.keys(data).map(function(k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
    }).join('&');
    xhr.send(params);
}

function resetSecurityKey() {
    if (!confirm('确定重置安全 Key 吗？\n重置后，火车头采集、简数采集、在线升级、小程序/App API 等需改用新 Key。')) {
        return;
    }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/set/resetSecurityKey', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var result = JSON.parse(xhr.responseText);
                if (result.status === 'y' && result.security_key) {
                    document.getElementById('security_key').value = result.security_key;
                    showToast(result.info, 'success');
                } else {
                    showToast(result.info || '重置失败', 'danger');
                }
            } catch(e) {
                showToast('重置失败', 'danger');
            }
        }
    };
    xhr.send('action=reset');
}

function saveEngine() {
    var engine = document.getElementById('tplEngine').value;
    if (engine !== 'legacy' && engine !== 'think') {
        showToast('请选择有效的模板引擎', 'danger');
        return;
    }
    if (!confirm('警告：当前模板文件是按当前引擎语法编写的，随意切换很可能导致前端崩溃（空白页/语法错误/样式错乱）！\n\n仅当您已用新引擎语法重写 app/index/view/ 下全部模板才应切换。\n\n确定要切换为 ' + (engine === 'think' ? 'ThinkTemplate（真·ThinkPHP 引擎）' : 'ZhiCms 自研引擎') + ' 吗？')) {
        return;
    }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/set/saveTplEngine', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var result = JSON.parse(xhr.responseText);
                showToast(result.info, result.status === 'y' ? 'success' : 'danger');
            } catch(e) {
                showToast('保存失败', 'danger');
            }
        }
    };
    xhr.send('engine=' + encodeURIComponent(engine));
}

function uploadImage(field) {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';

    input.onchange = function(e) {
        var file = e.target.files[0];
        if (!file) return;

        var formData = new FormData();
        formData.append('file', file);

        // 使用统一上传接口
        fetch('index.php?r=manage/File/upload&type=manage', {
            method: 'POST',
            body: formData
        })
        .then(function(response) { return response.text(); })
        .then(function(text) {
            console.log('[uploadImage response]', text ? text.substring(0, 300) : '(empty)');
            try {
                var result = JSON.parse(text);
                if (result.error === 0 && result.url) {
                    document.getElementById(field + '-input').value = result.url;
                    showToast('图片上传成功', 'success');
                    // 就地更新图片预览，不刷新页面
                    var preview = document.querySelector('#' + field + '-input').closest('.form-group').querySelector('img');
                    if (preview) {
                        preview.src = result.url;
                        preview.style.display = '';
                    }
                } else {
                    showToast(result.message || '上传失败', 'danger');
                }
            } catch(e) {
                showToast('上传失败', 'danger');
            }
        })
        .catch(function(error) {
            showToast('上传失败', 'danger');
        });
    };

    input.click();
}

function showToast(message, type = 'success') {
    // 创建toast提示；直接加 show 类并显式设置 opacity，避免依赖 Bootstrap JS 初始化（否则 .toast 默认隐藏不显示）
    var toast = document.createElement('div');
    toast.className = 'toast align-items-center text-white bg-' + type + ' border-0 position-fixed show';
    toast.setAttribute('role', 'alert');
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 250px; opacity: 1; transition: opacity .3s ease;';
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.parentElement.parentElement.remove()"></button>
        </div>
    `;

    document.body.appendChild(toast);

    // 3秒后淡出并移除
    setTimeout(function() {
        toast.style.opacity = '0';
        setTimeout(function() {
            if(toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 350);
    }, 3000);
}

// 键盘事件支持
document.addEventListener('DOMContentLoaded', function() {
    // 回车提交表单
    var forms = document.querySelectorAll('form');
    forms.forEach(function(form) {
        form.addEventListener('keypress', function(e) {
            if(e.which === 13 && e.target.tagName === 'INPUT' && e.target.type !== 'submit') {
                e.preventDefault();
            }
        });
    });
});

// SEO推送 - 手动推送
function doPush2() {
    var urls = document.getElementById('pushUrls').value.trim();
    if (!urls) { showToast('请输入要推送的URL', 'danger'); return; }
    var btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 推送中...';

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/set/seopush', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-rocket"></i> 开始推送';
            try {
                var r = JSON.parse(xhr.responseText);
                var box = document.getElementById('push-result');
                box.style.display = 'block';
                var cls = r.status === 'y' ? 'alert-success' : 'alert-danger';
                box.innerHTML = '<div class="alert '+cls+'">'+r.info+'</div>';
                showToast(r.info, r.status === 'y' ? 'success' : 'danger');
                if (r.status === 'y') { setTimeout(function(){ location.reload(); }, 1500); }
            } catch(e) {
                showToast('推送响应异常', 'danger');
            }
        }
    };
    var params = 'action=push&urls=' + encodeURIComponent(urls);
    if (document.getElementById('hash_field')) params += '&hash=' + encodeURIComponent(document.getElementById('hash_field').value);
    xhr.send(params);
}

function quickPush2(type) {
    var btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 推送中...';

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/set/seopush', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            btn.disabled = false;
            btn.innerHTML = type === 'recent' ? '<i class="fas fa-clock"></i> 推送最新 50 篇' : '<i class="fas fa-globe"></i> 推送全站';
            try {
                var r = JSON.parse(xhr.responseText);
                var box = document.getElementById('push-result');
                box.style.display = 'block';
                var cls = r.status === 'y' ? 'alert-success' : 'alert-danger';
                box.innerHTML = '<div class="alert '+cls+'">'+r.info+'</div>';
                showToast(r.info, r.status === 'y' ? 'success' : 'danger');
                if (r.status === 'y') { setTimeout(function(){ location.reload(); }, 2000); }
            } catch(e) {
                showToast('推送响应异常', 'danger');
            }
        }
    };
    var params = 'action=push_' + type;
    if (document.getElementById('hash_field')) params += '&hash=' + encodeURIComponent(document.getElementById('hash_field').value);
    xhr.send(params);
}

function clearLog2() {
    if (!confirm('确定要清空所有推送日志吗？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/set/seopush', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try { var r = JSON.parse(xhr.responseText); showToast(r.info, r.status === 'y' ? 'success' : 'danger'); } catch(e) {}
            location.reload();
        }
    };
    var params = 'action=clear_log';
    if (document.getElementById('hash_field')) params += '&hash=' + encodeURIComponent(document.getElementById('hash_field').value);
    xhr.send(params);
}
</script>
