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

<h1 class="page-title">
    <i class="fas fa-rocket"></i>
    SEO 推送
</h1>

<div class="row">
    <div class="col-lg-12">
        <div class="card mb-4">
            <div class="card-header"><i class="fas fa-cog"></i> 推送平台配置</div>
            <div class="card-body">
                <form id="seopush-form">

                    <!-- 百度站长平台 -->
                    <h5 class="section-title">
                        <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="section-title mt-4">
                        <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 -->
                    <h5 class="section-title mt-4">
                        <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="section-title mt-4">
                        <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>
            </div>
        </div>

        <!-- 手动推送 -->
        <div class="card mb-4">
            <div class="card-header"><i class="fas fa-paper-plane"></i> 手动推送</div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <form id="pushnow-form">
                            <div class="form-group">
                                <label class="font-weight-bold">推送 URL（每行一个，支持相对路径）</label>
                                <textarea class="form-control" id="pushUrls" name="urls" rows="8" 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="doPush()">
                                <i class="fas fa-rocket"></i> 开始推送
                            </button>
                            <button type="button" class="btn btn-outline-info mr-2" onclick="quickPush('recent')">
                                <i class="fas fa-clock"></i> 推送最新 50 篇
                            </button>
                            <button type="button" class="btn btn-outline-warning" onclick="quickPush('all')">
                                <i class="fas fa-globe"></i> 推送全站
                            </button>
                        </form>
                    </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-48 小时内生效</li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div id="push-result" class="mt-3 d-none"></div>
            </div>
        </div>

        <!-- 推送日志 -->
        <div class="card">
            <div class="card-header">
                <i class="fas fa-history"></i> 推送日志（最近 20 条）
                <button type="button" class="btn btn-sm btn-outline-danger float-right" onclick="clearLog()">
                    <i class="fas fa-trash"></i> 清空日志
                </button>
            </div>
            <div class="card-body" style="max-height:500px;overflow-y:auto;">
                <?php if (!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'=>'🔵','bing'=>'🟢','weibo'=>'🔴'][$plat] ?? '⚪';
                                    $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>
</div>

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

<script>
function doPush() {
    var urls = document.getElementById('pushUrls').value.trim();
    if (!urls) { showToast2('请输入要推送的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>';
                showToast2(r.info, r.status === 'y' ? 'success' : 'danger');
                if (r.status === 'y') { setTimeout(function(){ location.reload(); }, 1500); }
            } catch(e) {
                showToast2('推送响应异常', '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 quickPush(type) {
    var urls = '';
    if (type === 'recent') {
        urls = '<?php echo rtrim(obj('base/Base')->SiteConfig('hosturl'), "/"); ?>/view-1.html\n';
        urls += '# 实际将推送最新的50篇文章到各搜索引擎';
    } else {
        urls = '<?php echo rtrim(obj('base/Base')->SiteConfig('hosturl'), "/"); ?>/index.html\n';
        urls += '# 实际将推送全站核心页面到各搜索引擎';
    }
    document.getElementById('pushUrls').value = urls;
    // 直接调用 AJAX 全量推送
    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>';
                showToast2(r.info, r.status === 'y' ? 'success' : 'danger');
                if (r.status === 'y') { setTimeout(function(){ location.reload(); }, 2000); }
            } catch(e) {
                showToast2('推送响应异常', 'danger');
            }
        }
    };
    var actionParam = (type === 'recent') ? 'recent' : 'all';
    var params = 'action=push_' + actionParam;
    if (document.getElementById('hash_field')) params += '&hash=' + encodeURIComponent(document.getElementById('hash_field').value);
    xhr.send(params);
}

function clearLog() {
    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); showToast2(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);
}

function showToast2(message, type) {
    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);
    setTimeout(function(){ toast.style.opacity='0'; setTimeout(function(){ if(toast.parentNode) toast.parentNode.removeChild(toast); }, 350); }, 3000);
}

// 监听 push_* action 的处理
(function() {
    var origOpen = XMLHttpRequest.prototype.send;
    // 拦截 push_recent 和 push_all 转为服务端实际推送
})();
</script>
