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

admin_header('蜘蛛统计');

$log = __DIR__ . '/../cache/spider/spider.log';
$msg = '';

if($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'clear_spider_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_spider_log', 'clear spider access log');
}

$allLines = is_file($log) ? file($log, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : array();
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));

$summary = array(
    'today' => array('label'=>'今日', 'total'=>0, 'spiders'=>array()),
    'yesterday' => array('label'=>'昨日', 'total'=>0, 'spiders'=>array()),
    '7days' => array('label'=>'近7日', 'total'=>0, 'spiders'=>array()),
    '30days' => array('label'=>'近30日', 'total'=>0, 'spiders'=>array()),
    '1year' => array('label'=>'近1年', 'total'=>0, 'spiders'=>array()),
);
$domainCount = array();

foreach($allLines as $line){
    $p = explode("\t", $line);
    $timeStr = $p[0] ?? '';
    $domain = $p[1] ?? '';
    $spider = $p[2] ?? 'Unknown';
    $ts = strtotime($timeStr);
    if(!$ts) continue;
    if($domain) $domainCount[$domain] = ($domainCount[$domain] ?? 0) + 1;
    $date = date('Y-m-d', $ts);
    $keys = array();
    if($date === $today) $keys[] = 'today';
    if($date === $yesterday) $keys[] = 'yesterday';
    if($ts >= strtotime('-7 days')) $keys[] = '7days';
    if($ts >= strtotime('-30 days')) $keys[] = '30days';
    if($ts >= strtotime('-1 year')) $keys[] = '1year';
    foreach($keys as $key){
        $summary[$key]['total']++;
        $summary[$key]['spiders'][$spider] = ($summary[$key]['spiders'][$spider] ?? 0) + 1;
    }
}

$lines = array_reverse(array_slice($allLines, -500));

function admin_spider_display_url($domain, $url){
    $domain = trim((string)$domain);
    $url = trim((string)$url);
    if($url === '') $url = '/';
    if(preg_match('~^https?://~i', $url)) return $url;
    if($url[0] !== '/') $url = '/' . $url;
    $scheme = 'https';
    if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') $scheme = 'https';
    elseif(($_SERVER['SERVER_PORT'] ?? '') == '80' || in_array($domain, array('localhost','127.0.0.1'), true)) $scheme = 'http';
    if($domain === '') $domain = $_SERVER['HTTP_HOST'] ?? '';
    return $domain ? ($scheme . '://' . $domain . $url) : $url;
}
?>

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

<div class="grid">
<?php foreach($summary as $item): ?>
    <div class="stat">
        <strong><?php echo intval($item['total']); ?></strong>
        <span><?php echo admin_h($item['label']); ?>蜘蛛访问</span>
    </div>
<?php endforeach; ?>
</div>

<div class="card">
<h2>蜘蛛类型汇总</h2>
<div class="spider-type-grid">
<?php foreach($summary as $item): ?>
    <div class="spider-type-card">
        <div class="spider-type-title">
            <strong><?php echo admin_h($item['label']); ?></strong>
            <span><?php echo intval($item['total']); ?> 次</span>
        </div>
        <div class="spider-type-badges">
        <?php if(empty($item['spiders'])): ?>
            <em>暂无记录</em>
        <?php else: ?>
            <?php arsort($item['spiders']); foreach($item['spiders'] as $sp=>$num): ?>
                <span><?php echo admin_h($sp); ?><b><?php echo intval($num); ?></b></span>
            <?php endforeach; ?>
        <?php endif; ?>
        </div>
    </div>
<?php endforeach; ?>
</div>
</div>

<div class="card">
<h2>域名访问汇总</h2>
<table>
<tr><th>序号</th><th>域名</th><th>蜘蛛访问次数</th></tr>
<?php $i=1; arsort($domainCount); foreach($domainCount as $domain=>$num): ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo admin_h($domain); ?></td>
<td><?php echo intval($num); ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>

<div class="card">
<div class="log-tools">
    <h2>最近访问记录</h2>
    <form method="post" data-confirm="确定清空所有蜘蛛访问记录吗？清空后不可恢复。">
        <input type="hidden" name="action" value="clear_spider_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>URL路径</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><?php echo admin_h($p[3]??''); ?></td>
<td style="word-break:break-all"><?php echo admin_h(admin_spider_display_url($p[1]??'', $p[4]??'')); ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>

<?php admin_footer(); ?>
