<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include __DIR__ . '/config_writer.php';

admin_header('强引设置');

$forceLog = __DIR__ . '/../cache/spider/force.log';
$forceConfigFile = __DIR__ . '/../config/spider_force.php';
$forceConfig = is_file($forceConfigFile) ? include $forceConfigFile : array();
if(!is_array($forceConfig)) $forceConfig = array();
$forceConfig = array_merge(array(
    'enabled'=>0,
    'pass_weight'=>0,
    'status'=>302,
    'probability'=>30,
    'terminal'=>'all',
    'spider_all'=>0,
    'spiders'=>array('Baiduspider'),
    'dedupe'=>1,
    'start_time'=>'',
    'end_time'=>'',
    'target_links'=>array(),
    'rules'=>array(),
), $forceConfig);
$msg = '';

if($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'clear_spider_force_log'){
    $dir = dirname($forceLog);
    if(!is_dir($dir)) @mkdir($dir, 0755, true);
    file_put_contents($forceLog, '');
    $msg = '强引记录已清空。';
    if(function_exists('admin_oplog')) admin_oplog('clear_spider_force_log', 'clear spider force log');
}

if($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_spider_force'){
    $targetLinks = array();
    $lines = preg_split('/\r\n|\r|\n/', (string)($_POST['target_links'] ?? ''));
    foreach($lines as $line){
        $line = trim($line);
        if($line === '') continue;
        if(!preg_match('~^(https?://|/)~i', $line)) $line = '/' . $line;
        $targetLinks[] = $line;
    }
    $spiders = $_POST['force_spiders'] ?? array();
    if(!is_array($spiders)) $spiders = array();
    $allowSpiders = array('Baiduspider','Googlebot','Bingbot','Sogou','360Spider','Shenma','YandexBot','Bytespider');
    $spiders = array_values(array_intersect($allowSpiders, $spiders));
    if(!$spiders) $spiders = array('Baiduspider');
    $terminal = $_POST['terminal'] ?? 'all';
    if(!in_array($terminal, array('all','pc','mobile'), true)) $terminal = 'all';
    $probability = max(1, min(100, intval($_POST['probability'] ?? 30)));
    $forceConfig = array(
        'enabled' => !empty($_POST['force_enabled']) ? 1 : 0,
        'pass_weight' => !empty($_POST['pass_weight']) ? 1 : 0,
        'status' => !empty($_POST['pass_weight']) ? 301 : 302,
        'probability' => $probability,
        'terminal' => $terminal,
        'spider_all' => !empty($_POST['spider_all']) ? 1 : 0,
        'spiders' => $spiders,
        'dedupe' => !empty($_POST['dedupe']) ? 1 : 0,
        'start_time' => trim($_POST['start_time'] ?? ''),
        'end_time' => trim($_POST['end_time'] ?? ''),
        'target_links' => $targetLinks,
        'rules' => array(),
    );
    admin_export_php($forceConfigFile, $forceConfig);
    $msg = '蜘蛛强引配置已保存。';
    if(function_exists('admin_oplog')) admin_oplog('save_spider_force', count($targetLinks) . ' target links');
}

$forceLines = is_file($forceLog) ? file($forceLog, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : array();
$forceDisplayLines = array_reverse(array_slice($forceLines, -200));
$targetLinksText = implode("\n", array_map('strval', $forceConfig['target_links'] ?? array()));
$spiderOptions = array('Baiduspider'=>'百度蜘蛛','Googlebot'=>'Google 蜘蛛','Bingbot'=>'Bing 蜘蛛','Sogou'=>'搜狗蜘蛛','360Spider'=>'360 蜘蛛','Shenma'=>'神马蜘蛛','YandexBot'=>'Yandex 蜘蛛','Bytespider'=>'头条蜘蛛');
$hitCount = count($forceLines);
?>

<?php if($msg): ?><div class="notice"><?php echo admin_h($msg); ?></div><?php endif; ?>

<div class="force-hero">
    <div>
        <span class="force-kicker">Spider Redirect</span>
        <h2>强引设置</h2>
        <p>蜘蛛命中后按概率从目标链接池抽取链接跳转。开启权重传递时使用 301，否则使用 302。</p>
    </div>
    <div class="force-status-card <?php echo !empty($forceConfig['enabled']) ? 'is-on' : 'is-off'; ?>">
        <span><?php echo !empty($forceConfig['enabled']) ? '已启用' : '已关闭'; ?></span>
        <strong><?php echo intval($forceConfig['probability'] ?? 30); ?>%</strong>
        <em>当前强引概率</em>
    </div>
    <div class="force-status-card">
        <span>命中记录</span>
        <strong><?php echo intval($hitCount); ?></strong>
        <em>累计跳转次数</em>
    </div>
</div>

<form method="post" class="force-panel">
<input type="hidden" name="action" value="save_spider_force">
<section class="force-section">
    <div class="force-section-title">
        <span>01</span>
        <div><h3>基础开关</h3><p>控制是否启用、是否传递权重以及执行概率。</p></div>
    </div>
    <div class="force-switch-grid">
        <label class="force-toggle"><input type="checkbox" name="force_enabled" value="1" <?php echo !empty($forceConfig['enabled'])?'checked':''; ?>><span>强引开关</span><em>默认关闭，需要后台手动开启。</em></label>
        <label class="force-toggle"><input type="checkbox" name="pass_weight" value="1" <?php echo !empty($forceConfig['pass_weight'])?'checked':''; ?>><span>权重传递</span><em>开启后执行 301，否则仅 302。</em></label>
        <label class="force-toggle"><input type="checkbox" name="dedupe" value="1" <?php echo !empty($forceConfig['dedupe'])?'checked':''; ?>><span>链接去重</span><em>已命中的目标链接会优先避开。</em></label>
    </div>
    <div class="form-grid">
        <label>强引概率<input type="number" min="1" max="100" name="probability" value="<?php echo intval($forceConfig['probability'] ?? 30); ?>"></label>
        <label>蜘蛛终端<select name="terminal">
            <option value="all" <?php echo ($forceConfig['terminal'] ?? 'all')==='all'?'selected':''; ?>>全部</option>
            <option value="pc" <?php echo ($forceConfig['terminal'] ?? 'all')==='pc'?'selected':''; ?>>PC 蜘蛛</option>
            <option value="mobile" <?php echo ($forceConfig['terminal'] ?? 'all')==='mobile'?'selected':''; ?>>移动蜘蛛</option>
        </select></label>
        <label>开始时间<input type="datetime-local" name="start_time" value="<?php echo admin_h(($forceConfig['start_time'] ?? '') ? date('Y-m-d\TH:i', strtotime($forceConfig['start_time'])) : ''); ?>"></label>
        <label>结束时间<input type="datetime-local" name="end_time" value="<?php echo admin_h(($forceConfig['end_time'] ?? '') ? date('Y-m-d\TH:i', strtotime($forceConfig['end_time'])) : ''); ?>"></label>
    </div>
</section>

<section class="force-section">
    <div class="force-section-title">
        <span>02</span>
        <div><h3>蜘蛛类型</h3><p>可选全部蜘蛛，也可以只针对部分搜索蜘蛛执行。</p></div>
    </div>
    <div class="force-spider-grid">
        <label class="force-chip"><input type="checkbox" name="spider_all" value="1" <?php echo !empty($forceConfig['spider_all'])?'checked':''; ?>><span>全部蜘蛛</span></label>
        <?php foreach($spiderOptions as $sp=>$label): ?>
        <label class="force-chip"><input type="checkbox" name="force_spiders[]" value="<?php echo admin_h($sp); ?>" <?php echo in_array($sp, $forceConfig['spiders'] ?? array(), true)?'checked':''; ?>><span><?php echo admin_h($label); ?></span></label>
        <?php endforeach; ?>
    </div>
</section>

<section class="force-section">
    <div class="force-section-title">
        <span>03</span>
        <div><h3>目标链接池</h3><p>每行一个目标链接，系统会按概率随机抽取。</p></div>
    </div>
    <textarea name="target_links" class="force-target-textarea" rows="14" placeholder="https://www.example.com/news/{数字8}.html&#10;/news/{字母6}.html&#10;/news/{字符9}.html"><?php echo admin_h($targetLinksText); ?></textarea>
    <div class="force-token-box">
        <strong>支持标签</strong>
        <code>{数字8}</code><code>{字母6}</code><code>{字符9}</code><code>{日期}</code><code>{年}</code><code>{月}</code><code>{日}</code><code>{时}</code><code>{分}</code><code>{秒}</code>
        <span>支持区间：<code>http://a.com/100.html ~ http://a.com/500.html</code></span>
    </div>
</section>

<div class="force-submit-bar">
    <button type="submit">保存强引配置</button>
</div>
</form>

<div class="card">
<div class="log-tools">
    <h2>强引记录</h2>
    <form method="post" data-confirm="确定清空所有强引命中记录吗？清空后不可恢复。">
        <input type="hidden" name="action" value="clear_spider_force_log">
        <button class="btn small danger" type="submit">清空记录</button>
    </form>
</div>
<table>
<tr><th>序号</th><th>时间</th><th>域名</th><th>蜘蛛</th><th>IP</th><th>来源</th><th>目标</th><th>状态</th></tr>
<?php if(!$forceDisplayLines): ?>
<tr><td colspan="8">暂无强引命中记录</td></tr>
<?php endif; ?>
<?php $i=1; foreach($forceDisplayLines 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><?php echo admin_h($p[3]??''); ?></td>
<td style="word-break:break-all"><?php echo admin_h($p[4]??''); ?></td>
<td style="word-break:break-all"><?php echo admin_h($p[5]??''); ?></td>
<td><?php echo admin_h($p[6]??''); ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>

<?php admin_footer(); ?>
