<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

$filterDomain = isset($_GET['domain']) ? trim((string)$_GET['domain']) : '';
$filterDays = isset($_GET['days']) ? (int)$_GET['days'] : 30;
$filterDays = in_array($filterDays, array(7, 14, 30, 60, 90)) ? $filterDays : 30;
$filterSpider = isset($_GET['spider']) ? trim((string)$_GET['spider']) : '';
$tab = isset($_GET['tab']) ? trim((string)$_GET['tab']) : 'overview';

$dbError = '';
$dailyStats = array();
$summaryStats = array();
$topUrls = array();
$recentLogs = array();
$domainList = array();
$spiderDefs = spider_definitions();
$spiderDomainWhitelist = is_super_admin() ? null : user_domain_names();

try {
    ensure_spider_tables();
    $domainList = spider_domain_list();
    $dailyStats = spider_daily_stats($filterDays, $filterDomain, $spiderDomainWhitelist);
    $summaryStats = spider_summary_stats($filterDays, $filterDomain, $spiderDomainWhitelist);
    $topUrls = spider_top_urls($filterDays, $filterDomain, 30, $spiderDomainWhitelist);
    $recentLogs = spider_recent_logs($filterDomain, 100, $filterSpider, $spiderDomainWhitelist);
} catch (Exception $e) {
    $dbError = $e->getMessage();
}

$totalHits = 0;
foreach ($summaryStats as $row) {
    $totalHits += (int)$row['total_hits'];
}

$periodHits = array('30' => 0, '15' => 0, '7' => 0, '1' => 0);
try {
    $pdo = db_connection();
    $periods = array('30' => 30, '15' => 15, '7' => 7, '1' => 1);
    foreach ($periods as $key => $d) {
        $startDate = ($d === 1) ? date('Y-m-d') : date('Y-m-d', strtotime("-{$d} days"));
        $sql = "SELECT COALESCE(SUM(hits),0) FROM spider_daily WHERE day >= :start";
        $params = array(':start' => $startDate);
        $sql .= spider_build_domain_filter($filterDomain, $spiderDomainWhitelist, $params);
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $periodHits[$key] = (int)$stmt->fetchColumn();
    }
} catch (Exception $e) {}

$days = array();
$spiderNames = array();
foreach ($dailyStats as $row) {
    $days[$row['day']] = true;
    $spiderNames[$row['spider_name']] = true;
}
$days = array_keys($days);
$spiderNames = array_keys($spiderNames);

$seriesData = array();
foreach ($spiderNames as $sn) {
    $dayMap = array();
    foreach ($dailyStats as $row) {
        if ($row['spider_name'] === $sn) {
            $dayMap[$row['day']] = (int)$row['hits'];
        }
    }
    $data = array();
    foreach ($days as $d) {
        $data[] = isset($dayMap[$d]) ? $dayMap[$d] : 0;
    }
    $label = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['label'] : $sn;
    $color = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['color'] : '#94A3B8';
    $seriesData[] = array('name' => $label, 'data' => $data, 'color' => $color);
}

$pieData = array();
foreach ($summaryStats as $row) {
    $sn = $row['spider_name'];
    $label = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['label'] : $sn;
    $color = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['color'] : '#94A3B8';
    $pieData[] = array('name' => $label, 'value' => (int)$row['total_hits'], 'itemStyle' => array('color' => $color));
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 蜘蛛统计</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
    <style>
    .spider-stats-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(180px, 1fr)); gap:16px; margin-bottom:24px; }
    .spider-stat-card { background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:20px; text-align:center; transition:box-shadow .15s; }
    .spider-stat-card:hover { box-shadow:0 4px 16px rgba(0,0,0,.06); }
    .spider-stat-card .stat-dot { display:inline-block; width:10px; height:10px; border-radius:50%; margin-right:6px; }
    .spider-stat-card .stat-name { font-size:13px; color:#64748b; font-weight:600; }
    .spider-stat-card .stat-value { font-size:28px; font-weight:800; color:#0f172a; margin:8px 0 4px; }
    .spider-stat-card .stat-sub { font-size:12px; color:#94a3b8; }
    .chart-box { background:#fff; border:1px solid #e2e8f0; border-radius:14px; padding:20px; margin-bottom:24px; }
    .chart-box h3 { font-size:15px; color:#1e293b; margin:0 0 16px; font-weight:700; }
    .chart-container { width:100%; height:360px; }
    .charts-row { display:grid; grid-template-columns:2fr 1fr; gap:20px; margin-bottom:24px; }
    @media(max-width:900px) { .charts-row { grid-template-columns:1fr; } }
    .filter-bar { display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin-bottom:20px; }
    .filter-bar select, .filter-bar .filter-btn { padding:8px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:13px; color:#334155; background:#fff; cursor:pointer; }
    .filter-bar .filter-btn { background:#4f46e5; color:#fff; border-color:#4f46e5; font-weight:600; }
    .filter-bar .filter-btn:hover { background:#4338ca; }
    .tab-nav { display:flex; gap:4px; margin-bottom:20px; background:#f1f5f9; border-radius:12px; padding:4px; width:fit-content; }
    .tab-nav a { padding:8px 18px; border-radius:10px; font-size:13px; font-weight:600; color:#64748b; text-decoration:none; transition:all .15s; }
    .tab-nav a.active { background:#fff; color:#4f46e5; box-shadow:0 1px 4px rgba(0,0,0,.06); }
    .log-table { width:100%; border-collapse:collapse; font-size:13px; }
    .log-table th { background:#f8fafc; color:#64748b; font-weight:600; padding:10px 12px; text-align:left; border-bottom:2px solid #e2e8f0; white-space:nowrap; }
    .log-table td { padding:10px 12px; border-bottom:1px solid #f1f5f9; color:#334155; }
    .log-table tr:hover td { background:#f8fafc; }
    .log-table .url-cell { max-width:320px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
    .log-table .ua-cell { max-width:260px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; color:#94a3b8; }
    .spider-badge { display:inline-block; padding:2px 10px; border-radius:20px; font-size:11px; font-weight:700; color:#fff; }
    .status-badge { display:inline-block; padding:2px 8px; border-radius:8px; font-size:11px; font-weight:600; }
    .status-2xx { background:#dcfce7; color:#15803d; }
    .status-3xx { background:#dbeafe; color:#1d4ed8; }
    .status-4xx { background:#fef9c3; color:#a16207; }
    .status-5xx { background:#fef2f2; color:#dc2626; }
    .empty-state { text-align:center; padding:60px 20px; color:#94a3b8; }
    .empty-state svg { width:64px; height:64px; margin-bottom:16px; opacity:.4; }
    .total-card { background:linear-gradient(135deg,#4f46e5,#6366f1); border-radius:14px; padding:24px 32px; color:#fff; margin-bottom:24px; display:flex; align-items:center; gap:0; }
    .total-card .total-main { flex:0 0 auto; margin-right:32px; }
    .total-card .total-num { font-size:42px; font-weight:800; line-height:1; }
    .total-card .total-label { font-size:14px; opacity:.85; margin-top:4px; }
    .total-card .total-days { font-size:13px; opacity:.7; }
    .total-card .period-grid { display:flex; flex:1; gap:0; }
    .total-card .period-item { flex:1; text-align:center; padding:12px 0; border-left:1px solid rgba(255,255,255,.15); }
    .total-card .period-item:first-child { border-left:none; }
    .total-card .period-value { font-size:26px; font-weight:800; line-height:1; }
    .total-card .period-label { font-size:12px; opacity:.7; margin-top:6px; }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('spider_stats', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>蜘蛛访问统计</h1><p>监控百度、谷歌、必应、搜狗等搜索引擎蜘蛛的抓取情况（已启用 UA + IP 段 + 反向 DNS 校验）</p></div>
            </header>

            <?php if ($dbError !== ''): ?>
                <div class="mini-item" style="margin-bottom:16px; border-color:rgba(220,38,38,0.18); background:rgba(220,38,38,0.06);"><strong style="color:#dc2626;">数据库错误</strong><p style="margin:0; color:#b91c1c;"><?php echo e($dbError); ?></p></div>
            <?php endif; ?>

            <div class="mini-item" style="margin-bottom:16px; border-color:rgba(37,99,235,0.18); background:rgba(37,99,235,0.06);">
                <strong style="color:#1d4ed8;">真实性校验已开启</strong>
                <p style="margin:6px 0 0; color:#1e40af;">系统不再仅凭 User-Agent 识别蜘蛛；必须命中官方 IP 段或通过反向 DNS 正反查校验后，才会写入蜘蛛统计。伪造 Baiduspider、Googlebot 等 UA 的普通访问不会计入统计。</p>
            </div>

            <div class="filter-bar">
                <select id="filterDomain" onchange="applyFilter()">
                    <option value="">全部域名</option>
                    <?php foreach ($domainList as $d): ?>
                        <option value="<?php echo e($d); ?>" <?php echo $filterDomain === $d ? 'selected' : ''; ?>><?php echo e($d); ?></option>
                    <?php endforeach; ?>
                </select>
                <select id="filterDays" onchange="applyFilter()">
                    <option value="7" <?php echo $filterDays === 7 ? 'selected' : ''; ?>>近7天</option>
                    <option value="14" <?php echo $filterDays === 14 ? 'selected' : ''; ?>>近14天</option>
                    <option value="30" <?php echo $filterDays === 30 ? 'selected' : ''; ?>>近30天</option>
                    <option value="60" <?php echo $filterDays === 60 ? 'selected' : ''; ?>>近60天</option>
                    <option value="90" <?php echo $filterDays === 90 ? 'selected' : ''; ?>>近90天</option>
                </select>
                <?php if ($tab === 'logs'): ?>
                <select id="filterSpider" onchange="applyFilter()">
                    <option value="">全部蜘蛛</option>
                    <?php foreach ($spiderDefs as $sn => $def): ?>
                        <option value="<?php echo e($sn); ?>" <?php echo $filterSpider === $sn ? 'selected' : ''; ?>><?php echo e($def['label']); ?></option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
            </div>

            <div class="tab-nav">
                <a href="?tab=overview&domain=<?php echo urlencode($filterDomain); ?>&days=<?php echo $filterDays; ?>" class="<?php echo $tab === 'overview' ? 'active' : ''; ?>">总览</a>
                <a href="?tab=urls&domain=<?php echo urlencode($filterDomain); ?>&days=<?php echo $filterDays; ?>" class="<?php echo $tab === 'urls' ? 'active' : ''; ?>">热门URL</a>
                <a href="?tab=logs&domain=<?php echo urlencode($filterDomain); ?>&days=<?php echo $filterDays; ?>" class="<?php echo $tab === 'logs' ? 'active' : ''; ?>">访问日志</a>
            </div>

            <?php if ($tab === 'overview'): ?>

            <div class="total-card">
                <div class="total-main">
                    <div class="total-num"><?php echo number_format($totalHits); ?></div>
                    <div class="total-label">蜘蛛总访问次数</div>
                    <div class="total-days">近 <?php echo $filterDays; ?> 天<?php echo $filterDomain !== '' ? ' · ' . e($filterDomain) : ''; ?></div>
                </div>
                <div class="period-grid">
                    <div class="period-item">
                        <div class="period-value"><?php echo number_format($periodHits['30']); ?></div>
                        <div class="period-label">近30天</div>
                    </div>
                    <div class="period-item">
                        <div class="period-value"><?php echo number_format($periodHits['15']); ?></div>
                        <div class="period-label">近15天</div>
                    </div>
                    <div class="period-item">
                        <div class="period-value"><?php echo number_format($periodHits['7']); ?></div>
                        <div class="period-label">近7天</div>
                    </div>
                    <div class="period-item">
                        <div class="period-value"><?php echo number_format($periodHits['1']); ?></div>
                        <div class="period-label">今天</div>
                    </div>
                </div>
            </div>

            <?php if (empty($summaryStats)): ?>
                <div class="empty-state">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><path d="M8 15h8M9 9h.01M15 9h.01"/></svg>
                    <p>暂无蜘蛛访问数据，蜘蛛来访后将自动记录。</p>
                </div>
            <?php else: ?>

            <div class="spider-stats-grid">
                <?php foreach ($summaryStats as $row): ?>
                    <?php
                        $sn = $row['spider_name'];
                        $label = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['label'] : $sn;
                        $color = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['color'] : '#94A3B8';
                    ?>
                    <div class="spider-stat-card">
                        <div class="stat-name"><span class="stat-dot" style="background:<?php echo $color; ?>"></span><?php echo e($label); ?></div>
                        <div class="stat-value"><?php echo number_format((int)$row['total_hits']); ?></div>
                        <div class="stat-sub">2xx:<?php echo (int)$row['s2']; ?> · 3xx:<?php echo (int)$row['s3']; ?> · 4xx:<?php echo (int)$row['s4']; ?> · 5xx:<?php echo (int)$row['s5']; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="charts-row">
                <div class="chart-box">
                    <h3>蜘蛛访问趋势</h3>
                    <div class="chart-container" id="trendChart"></div>
                </div>
                <div class="chart-box">
                    <h3>蜘蛛占比</h3>
                    <div class="chart-container" id="pieChart"></div>
                </div>
            </div>

            <?php endif; ?>

            <?php elseif ($tab === 'urls'): ?>

            <section class="page-card">
                <h3 style="margin:0 0 16px; font-size:15px; font-weight:700; color:#1e293b;">热门被爬取URL（近<?php echo $filterDays; ?>天）</h3>
                <?php if (empty($topUrls)): ?>
                    <div class="empty-state"><p>暂无数据</p></div>
                <?php else: ?>
                    <div style="overflow-x:auto;">
                    <table class="log-table">
                        <thead><tr><th>URL</th><th>蜘蛛</th><th>访问次数</th></tr></thead>
                        <tbody>
                        <?php foreach ($topUrls as $row): ?>
                            <?php
                                $sn = $row['spider_name'];
                                $label = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['label'] : $sn;
                                $color = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['color'] : '#94A3B8';
                            ?>
                            <tr>
                                <td class="url-cell" title="<?php echo e($row['url']); ?>"><?php echo e($row['url']); ?></td>
                                <td><span class="spider-badge" style="background:<?php echo $color; ?>"><?php echo e($label); ?></span></td>
                                <td><strong><?php echo number_format((int)$row['hits']); ?></strong></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    </div>
                <?php endif; ?>
            </section>

            <?php elseif ($tab === 'logs'): ?>

            <section class="page-card">
                <h3 style="margin:0 0 16px; font-size:15px; font-weight:700; color:#1e293b;">最近访问日志（最新100条）</h3>
                <?php if (empty($recentLogs)): ?>
                    <div class="empty-state"><p>暂无日志</p></div>
                <?php else: ?>
                    <div style="overflow-x:auto;">
                    <table class="log-table">
                        <thead><tr><th>时间</th><th>蜘蛛</th><th>域名</th><th>URL</th><th>状态码</th><th>IP</th><th>User-Agent</th></tr></thead>
                        <tbody>
                        <?php foreach ($recentLogs as $row): ?>
                            <?php
                                $sn = $row['spider_name'];
                                $label = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['label'] : $sn;
                                $color = isset($spiderDefs[$sn]) ? $spiderDefs[$sn]['color'] : '#94A3B8';
                                $sc = (int)$row['status_code'];
                                $scClass = 'status-2xx';
                                if ($sc >= 300 && $sc < 400) $scClass = 'status-3xx';
                                elseif ($sc >= 400 && $sc < 500) $scClass = 'status-4xx';
                                elseif ($sc >= 500) $scClass = 'status-5xx';
                            ?>
                            <tr>
                                <td style="white-space:nowrap;"><?php echo e($row['created_at']); ?></td>
                                <td><span class="spider-badge" style="background:<?php echo $color; ?>"><?php echo e($label); ?></span></td>
                                <td><?php echo e($row['domain']); ?></td>
                                <td class="url-cell" title="<?php echo e($row['url']); ?>"><?php echo e($row['url']); ?></td>
                                <td><span class="status-badge <?php echo $scClass; ?>"><?php echo $sc; ?></span></td>
                                <td><?php echo e($row['ip']); ?></td>
                                <td class="ua-cell" title="<?php echo e($row['user_agent']); ?>"><?php echo e($row['user_agent']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    </div>
                <?php endif; ?>
            </section>

            <?php endif; ?>

        </div>
    </main>
</div>

<script>
function applyFilter() {
    var domain = document.getElementById('filterDomain').value;
    var days = document.getElementById('filterDays').value;
    var spider = document.getElementById('filterSpider') ? document.getElementById('filterSpider').value : '';
    var tab = '<?php echo e($tab); ?>';
    var url = '/admin/spider-stats/index.php?tab=' + tab + '&domain=' + encodeURIComponent(domain) + '&days=' + days;
    if (spider) url += '&spider=' + encodeURIComponent(spider);
    window.location.href = url;
}

<?php if ($tab === 'overview' && !empty($summaryStats)): ?>
(function(){
    var days = <?php echo json_encode($days); ?>;
    var series = <?php echo json_encode($seriesData, JSON_UNESCAPED_UNICODE); ?>;
    var pieData = <?php echo json_encode($pieData, JSON_UNESCAPED_UNICODE); ?>;

    var trendEl = document.getElementById('trendChart');
    if (trendEl) {
        var chart = echarts.init(trendEl);
        var seriesArr = [];
        var legendData = [];
        series.forEach(function(s) {
            legendData.push(s.name);
            seriesArr.push({
                name: s.name,
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: { width: 2.5, color: s.color },
                itemStyle: { color: s.color },
                areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: s.color + '30' },
                    { offset: 1, color: s.color + '05' }
                ]) },
                data: s.data
            });
        });
        chart.setOption({
            tooltip: { trigger: 'axis' },
            legend: { data: legendData, bottom: 0, textStyle: { fontSize: 12, color: '#64748b' } },
            grid: { left: 50, right: 20, top: 20, bottom: 40 },
            xAxis: { type: 'category', data: days, axisLabel: { fontSize: 11, color: '#94a3b8' }, axisLine: { lineStyle: { color: '#e2e8f0' } } },
            yAxis: { type: 'value', axisLabel: { fontSize: 11, color: '#94a3b8' }, splitLine: { lineStyle: { color: '#f1f5f9' } } },
            series: seriesArr
        });
        window.addEventListener('resize', function() { chart.resize(); });
    }

    var pieEl = document.getElementById('pieChart');
    if (pieEl) {
        var pie = echarts.init(pieEl);
        pie.setOption({
            tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
            series: [{
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['50%', '45%'],
                label: { fontSize: 12, color: '#475569' },
                emphasis: { label: { fontWeight: 'bold', fontSize: 14 } },
                data: pieData
            }]
        });
        window.addEventListener('resize', function() { pie.resize(); });
    }
})();
<?php endif; ?>
</script>
</body>
</html>
