<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include __DIR__ . '/config_writer.php';
include_once __DIR__ . '/../inc/push_center.php';
admin_header('推送管理');

$configFile = __DIR__ . '/../config/push_center.php';
$cfg = is_file($configFile) ? include $configFile : push_center_config();
if(!is_array($cfg)) $cfg = push_center_config();
$domainsCfg = is_file(__DIR__ . '/../config/domain.php') ? include __DIR__ . '/../config/domain.php' : array();
if(!is_array($domainsCfg)) $domainsCfg = array();
$themes = admin_site_themes();
$msg = '';
$log = __DIR__ . '/../cache/push/push_center.log';

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

    if($action === 'save_settings'){
        $cfg['realtime_enabled'] = !empty($_POST['realtime_enabled']);
        $cfg['baidu']['enabled'] = !empty($_POST['baidu_enabled']);
        $cfg['bing']['enabled'] = !empty($_POST['bing_enabled']);
        $cfg['bing']['api_key'] = trim($_POST['bing_api_key'] ?? '');
        if(!isset($cfg['baidu']['domains']) || !is_array($cfg['baidu']['domains'])) $cfg['baidu']['domains'] = array();
        admin_export_php($configFile, $cfg);
        $msg = '推送开关与 API 参数已保存。';
        if(function_exists('admin_oplog')) admin_oplog('save_push_settings', $msg);
    }

    if($action === 'save_baidu_domain'){
        $domain = trim($_POST['domain'] ?? '');
        $token = trim($_POST['token'] ?? '');
        $protocol = ($_POST['protocol'] ?? 'https') === 'http' ? 'http' : 'https';
        if($domain && isset($domainsCfg[$domain])){
            if(!isset($cfg['baidu']['domains']) || !is_array($cfg['baidu']['domains'])) $cfg['baidu']['domains'] = array();
            $cfg['baidu']['domains'][$domain] = array(
                'site' => $domain,
                'token' => $token,
                'protocol' => $protocol,
            );
            admin_export_php($configFile, $cfg);
            $msg = '百度域名 Token 已保存：' . $domain;
            if(function_exists('admin_oplog')) admin_oplog('save_baidu_token', $domain);
        }else{
            $msg = '请选择有效域名。';
        }
    }

    if($action === 'delete_baidu_domain'){
        $domain = trim($_POST['domain'] ?? '');
        if($domain && isset($cfg['baidu']['domains'][$domain])){
            unset($cfg['baidu']['domains'][$domain]);
            admin_export_php($configFile, $cfg);
            $msg = '百度域名 Token 已删除：' . $domain;
            if(function_exists('admin_oplog')) admin_oplog('delete_baidu_token', $domain);
        }else{
            $msg = '未找到需要删除的百度域名配置。';
        }
    }

    if($action === 'clear_push_log'){
        $dir = dirname($log);
        if(!is_dir($dir)) @mkdir($dir, 0755, true);
        file_put_contents($log, '');
        $msg = '推送日志已清空。';
        if(function_exists('admin_oplog')) admin_oplog('clear_push_log', 'clear push center log');
    }

    if($action === 'test_push'){
        $domain = trim($_POST['domain'] ?? '');
        $path = trim($_POST['url'] ?? '');
        $engines = $_POST['engines'] ?? array();
        if(!is_array($engines)) $engines = array();

        if(!$domain || !$path){
            $msg = '请选择域名并填写 URL。';
        } elseif(empty($engines)) {
            $msg = '请至少选择百度或 Bing。';
        } else {
            $url = push_center_make_url($domain, $path);
            $results = push_center_submit($domain, $url, $engines, true);
            $parts = array();
            foreach($results as $engine=>$res){
                $parts[] = strtoupper($engine) . '：' . $res[1];
            }
            $msg = implode('；', $parts);
            if(function_exists('admin_oplog')) admin_oplog('test_push', $domain . ' ' . $url);
        }
    }
}

$cfg = is_file($configFile) ? include $configFile : $cfg;
if(!is_array($cfg)) $cfg = push_center_config();
$lines = is_file($log) ? array_reverse(array_slice(file($log, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES), -100)) : array();
$baiduDomains = $cfg['baidu']['domains'] ?? array();
if(!is_array($baiduDomains)) $baiduDomains = array();
$configuredBaiduCount = 0;
foreach($baiduDomains as $row){
    if(trim((string)($row['token'] ?? '')) !== '') $configuredBaiduCount++;
}
?>
<?php if($msg): ?><div class="notice"><?php echo admin_h($msg); ?></div><?php endif; ?>

<div class="cc-dashboard push-overview">
    <div><span>实时推送</span><strong><?php echo !empty($cfg['realtime_enabled']) ? '开启' : '关闭'; ?></strong></div>
    <div><span>百度推送</span><strong><?php echo !empty($cfg['baidu']['enabled']) ? '开启' : '关闭'; ?></strong></div>
    <div><span>Bing API</span><strong><?php echo !empty($cfg['bing']['enabled']) ? '开启' : '关闭'; ?></strong></div>
    <div><span>百度 Token</span><strong><?php echo intval($configuredBaiduCount); ?></strong></div>
</div>

<div class="card">
<h2>推送开关</h2>
<form method="post" class="config-form">
<input type="hidden" name="action" value="save_settings">

<div class="switch-grid two">
<label class="switch-card">
    <input type="checkbox" name="realtime_enabled" <?php echo !empty($cfg['realtime_enabled']) ? 'checked' : ''; ?>>
    <span>实时推送总开关</span>
    <em>开启后，内容中心发布或更新已发布内容时可实时提交 URL。</em>
</label>
<label class="switch-card">
    <input type="checkbox" name="baidu_enabled" <?php echo !empty($cfg['baidu']['enabled']) ? 'checked' : ''; ?>>
    <span>百度推送</span>
    <em>需要每个域名单独配置百度站长平台 Token。</em>
</label>
<label class="switch-card">
    <input type="checkbox" name="bing_enabled" <?php echo !empty($cfg['bing']['enabled']) ? 'checked' : ''; ?>>
    <span>Bing API</span>
    <em>需要填写 Bing Webmaster API Key。</em>
</label>
</div>

<div class="form-section">
    <div class="section-title">
        <span>API</span>
        <div>
            <h3>Bing API Key</h3>
            <p>百度 Token 在下方按域名单独配置；Bing 使用统一 API Key。</p>
        </div>
    </div>
    <label>Bing API Key<input name="bing_api_key" value="<?php echo admin_h($cfg['bing']['api_key'] ?? ''); ?>" placeholder="请输入 Bing Webmaster API Key"></label>
</div>

<p><button>保存推送配置</button></p>
</form>
</div>

<div class="card">
<h2>百度主动推送 Token 配置</h2>
<form method="post" class="config-form">
<input type="hidden" name="action" value="save_baidu_domain">
<div class="form-grid">
<label>选择域名
<select name="domain" id="baidu-token-domain">
<?php foreach($domainsCfg as $d=>$v): if($d==='localhost'||$d==='127.0.0.1') continue; ?>
<option value="<?php echo admin_h($d); ?>"><?php $themeKey = $v['theme'] ?? ''; echo admin_h($d . ' / ' . (($themes[$themeKey] ?? $themeKey) . ($themeKey ? ' / ' . $themeKey : ''))); ?></option>
<?php endforeach; ?>
</select>
</label>
<label>协议
<select name="protocol" id="baidu-token-protocol">
<option value="https">https</option>
<option value="http">http</option>
</select>
</label>
<label>百度 Token<input name="token" id="baidu-token-input" placeholder="百度站长平台 token"></label>
</div>
<p><button>保存百度 Token</button></p>
</form>

<h3 class="push-subtitle">已配置参数</h3>
<table class="content-record-table">
<tr><th>域名</th><th>协议</th><th>站点参数</th><th>Token</th><th>状态</th><th>操作</th></tr>
<?php $hasBaiduRows=false; foreach($baiduDomains as $domain=>$row): $hasBaiduRows=true; $token=trim((string)($row['token'] ?? '')); ?>
<tr>
<td><strong><?php echo admin_h($domain); ?></strong></td>
<td><?php echo admin_h($row['protocol'] ?? 'https'); ?></td>
<td><?php echo admin_h($row['site'] ?? $domain); ?></td>
<td><code><?php echo $token !== '' ? admin_h(substr($token, 0, min(6, strlen($token))) . str_repeat('*', max(4, min(18, max(0, strlen($token) - 6))))) : '未填写'; ?></code></td>
<td><?php echo $token !== '' ? '已配置' : '缺少 Token'; ?></td>
<td class="actions-cell"><div class="row-actions">
<button type="button" class="btn small ghost" data-fill-baidu="<?php echo admin_h($domain); ?>">编辑</button>
<form method="post" data-confirm="确定删除该域名的百度推送配置吗？">
    <input type="hidden" name="action" value="delete_baidu_domain">
    <input type="hidden" name="domain" value="<?php echo admin_h($domain); ?>">
    <button type="submit" class="btn small danger">删除</button>
</form>
</div></td>
</tr>
<?php endforeach; ?>
<?php if(!$hasBaiduRows): ?><tr><td colspan="6">暂无百度推送参数，请先选择域名并保存 Token。</td></tr><?php endif; ?>
</table>
</div>

<div class="card">
<h2>测试推送（百度 / Bing）</h2>
<form method="post" class="config-form">
<input type="hidden" name="action" value="test_push">
<div class="form-grid two">
<label>选择域名
<select name="domain" id="push-domain">
<?php foreach($domainsCfg as $d=>$v): if($d==='localhost'||$d==='127.0.0.1') continue; ?>
<option value="<?php echo admin_h($d); ?>"><?php $themeKey = $v['theme'] ?? ''; echo admin_h($d . ' / ' . (($themes[$themeKey] ?? $themeKey) . ($themeKey ? ' / ' . $themeKey : ''))); ?></option>
<?php endforeach; ?>
</select>
</label>
<label>推送 URL
<input name="url" id="push-url" placeholder="/news/001.html 或 https://www.example.com/news/001.html">
</label>
</div>
<div class="engine-checks">
<label><input type="checkbox" name="engines[]" value="baidu" checked> 百度</label>
<label><input type="checkbox" name="engines[]" value="bing"> Bing</label>
</div>
<p><button>测试推送</button></p>
</form>
</div>

<div class="card">
<div class="log-tools">
    <h2>推送日志</h2>
    <form method="post" data-confirm="确定清空所有推送日志吗？清空后不可恢复。">
        <input type="hidden" name="action" value="clear_push_log">
        <button class="btn small danger" type="submit">清空日志</button>
    </form>
</div>
<table>
<tr><th>序号</th><th>时间</th><th>引擎</th><th>域名</th><th>URL</th><th>结果</th></tr>
<?php if(!$lines): ?><tr><td colspan="6">暂无推送日志</td></tr><?php endif; ?>
<?php $i=1; foreach($lines as $line): $p=explode("\t",$line); ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo admin_h($p[0]??''); ?></td>
<td><?php echo admin_h($p[1]??''); ?></td>
<td><?php echo admin_h($p[2]??''); ?></td>
<td style="word-break:break-all"><?php echo admin_h($p[3]??''); ?></td>
<td><?php echo admin_h($p[4]??''); ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>

<script>
(function(){
    var baiduConfigs = <?php echo json_encode($baiduDomains, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var baiduDomain = document.getElementById('baidu-token-domain');
    var baiduProtocol = document.getElementById('baidu-token-protocol');
    var baiduToken = document.getElementById('baidu-token-input');
    function fillBaiduConfig(domainValue){
        if(!baiduDomain || !baiduProtocol || !baiduToken) return;
        var cfg = baiduConfigs[domainValue] || {};
        baiduDomain.value = domainValue;
        baiduProtocol.value = cfg.protocol || 'https';
        baiduToken.value = cfg.token || '';
    }
    if(baiduDomain){
        baiduDomain.addEventListener('change', function(){ fillBaiduConfig(baiduDomain.value); });
        fillBaiduConfig(baiduDomain.value);
    }
    document.querySelectorAll('[data-fill-baidu]').forEach(function(btn){
        btn.addEventListener('click', function(){
            fillBaiduConfig(btn.getAttribute('data-fill-baidu'));
            if(baiduToken) baiduToken.focus();
        });
    });

    var domain = document.getElementById('push-domain');
    var url = document.getElementById('push-url');
    function fill(){
        if(domain && url && !url.value){
            url.value = 'https://' + domain.value + '/';
        }
    }
    if(domain){
        domain.addEventListener('change', function(){
            url.value='https://' + domain.value + '/';
        });
        fill();
    }
})();
</script>

<?php admin_footer(); ?>