<?php
$file = 'count.json';
$d = json_decode(file_get_contents($file), true);

// 获取搜索和筛选参数
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$filter = isset($_GET['filter']) ? $_GET['filter'] : ''; // 'new' | 'old' | ''
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'desc'; // 'desc' | 'asc'

echo "<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>访问统计</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Microsoft YaHei', Arial, sans-serif; padding: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h2, h3 { color: #333; margin-bottom: 15px; border-bottom: 2px solid #eee; padding-bottom: 10px; }
        table { border-collapse: collapse; width: 100%; margin: 10px 0; }
        th, td { border: 1px solid #ddd; padding: 10px; text-align: left; font-size: 13px; vertical-align: top; }
        th { background-color: #4a90e2; color: white; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        .new { color: #28a745; font-weight: bold; }
        .old { color: #6c757d; }
        .summary-card { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 8px; margin-bottom: 25px; }
        .stat-box { text-align: center; padding: 10px; background: rgba(255,255,255,0.1); border-radius: 6px; }
        .stat-box span { display: block; font-size: 28px; font-weight: bold; margin-bottom: 5px; }
        .stat-box label { font-size: 13px; opacity: 0.9; }
        .row-title { grid-column: 1 / -1; font-size: 16px; font-weight: bold; margin-bottom: 10px; border-bottom: 1px solid rgba(255,255,255,0.3); padding-bottom: 5px; margin-top: 10px; }
        .search-container { background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; border: 1px solid #e9ecef; }
        .search-container input { padding: 10px 15px; border: 1px solid #ddd; border-radius: 4px; width: 300px; font-size: 14px; outline: none; }
        .search-container input:focus { border-color: #4a90e2; }
        .search-container button { padding: 10px 25px; background: #4a90e2; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: bold; }
        .search-container button:hover { background: #357abd; }
        .search-container button.reset-btn { background: #6c757d; }
        .search-container button.reset-btn:hover { background: #5a6268; }
        .filter-btn { padding: 8px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; margin-right: 8px; }
        .filter-btn.active { font-weight: bold; box-shadow: 0 0 0 2px rgba(0,0,0,0.2); }
        .filter-btn.all { background: #e9ecef; color: #333; }
        .filter-btn.all.active { background: #343a40; color: white; }
        .filter-btn.new-btn { background: #d4edda; color: #155724; }
        .filter-btn.new-btn.active { background: #28a745; color: white; }
        .filter-btn.old-btn { background: #e2e3e5; color: #383d41; }
        .filter-btn.old-btn.active { background: #6c757d; color: white; }
        .sort-btn { padding: 6px 12px; background: #17a2b8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px; }
        .sort-btn:hover { background: #138496; }
        .sort-btn.active { background: #0d6efd; }
        .section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .section-header .buttons { display: flex; align-items: center; gap: 10px; }
        .total-section { border: 2px solid #ffc107; padding: 15px; background: #fffcf0; border-radius: 8px; margin-top: 20px; }
        /* 归属地样式 */
        .ip-cell { line-height: 1.4; }
        .location-text { display: block; font-size: 11px; color: #888; margin-top: 4px; font-weight: normal; }
        .loading-loc { color: #ccc; font-style: italic; font-size: 11px; }
    </style>
</head>
<body>
    <div class='container'>
        <h2>📊 访问统计系统</h2>";

// 统计概览数据获取
$totalPeople = isset($d['total_ip']) ? count($d['total_ip']) : 0;
$totalVisits = $d['total_num'] ?? 0;

$todayNew = $d['today_new_num'] ?? 0;
$todayVisitors = $d['today_visitor_num'] ?? 0;
$todayVisits = $d['today_num'] ?? 0;

$yestNew = $d['yest_new_num'] ?? 0;
$yestVisitors = $d['yest_visitor_num'] ?? 0;
$yestVisits = $d['yest_num'] ?? 0;

$dayBeforeNew = $d['day_before_new_num'] ?? 0;
$dayBeforeVisitors = $d['day_before_visitor_num'] ?? 0;
$dayBeforeVisits = $d['day_before_num'] ?? 0;

echo "<div class='summary-card'>
    <div class='row-title'>第1行 - 访问人数统计</div>
    <div class='stat-box'><span>{$todayVisitors}</span><label>今日访问人数</label></div>
    <div class='stat-box'><span>{$yestVisitors}</span><label>昨日访问人数</label></div>
    <div class='stat-box'><span>{$dayBeforeVisitors}</span><label>前天访问人数</label></div>
    <div class='stat-box'><span>{$totalPeople}</span><label>历史总人数</label></div>
    
    <div class='row-title'>第2行 - 新增人数统计</div>
    <div class='stat-box'><span>{$todayNew}</span><label>今日新增人数</label></div>
    <div class='stat-box'><span>{$yestNew}</span><label>昨日新增人数</label></div>
    <div class='stat-box'><span>{$dayBeforeNew}</span><label>前天新增人数</label></div>
    <div class='stat-box'><span>--</span><label>历史总新增</label></div>
    
    <div class='row-title'>第3行 - 访问次数统计</div>
    <div class='stat-box'><span>{$todayVisits}</span><label>今日访问次数</label></div>
    <div class='stat-box'><span>{$yestVisits}</span><label>昨日访问次数</label></div>
    <div class='stat-box'><span>{$dayBeforeVisits}</span><label>前天访问次数</label></div>
    <div class='stat-box'><span>{$totalVisits}</span><label>历史总次数</label></div>
</div>";

// 构建URL辅助函数
function buildUrl($newParams = []) {
    $current = $_GET;
    foreach ($newParams as $key => $value) {
        $current[$key] = $value;
    }
    $parts = [];
    foreach ($current as $k => $v) {
        if ($v !== '' && $v !== null) {
            $parts[] = $k . '=' . urlencode($v);
        }
    }
    return '?' . implode('&', $parts);
}

// --- 搜索和筛选框 ---
echo "<div class='search-container'>
    <label>🔍 <strong>全局搜索：</strong></label>
    <input type='text' id='searchInput' value='" . htmlspecialchars($search) . "' placeholder='输入IP地址或访问时间...'>
    <button onclick='doSearch()'>搜索</button>
    <button onclick='clearSearch()' class='reset-btn'>重置</button>
</div>";

echo "<div class='search-container' style='background: #e8f4f8; border-color: #b8daff;'>
    <label>📊 <strong>快速筛选：</strong></label>
    <button class='filter-btn all" . ($filter == '' ? ' active' : '') . "' onclick='window.location.href=\"" . buildUrl(['filter' => '']) . "\"'>全部</button>
    <button class='filter-btn new-btn" . ($filter == 'new' ? ' active' : '') . "' onclick='window.location.href=\"" . buildUrl(['filter' => 'new']) . "\"'>只看新增</button>
    <button class='filter-btn old-btn" . ($filter == 'old' ? ' active' : '') . "' onclick='window.location.href=\"" . buildUrl(['filter' => 'old']) . "\"'>只看回头</button>
</div>";

// --- 合并所有数据源（用于分类统计）---
$allVisits = [];
if (isset($d['today_visits']) && is_array($d['today_visits'])) {
    $allVisits = array_merge($allVisits, $d['today_visits']);
}
if (isset($d['yest_visits']) && is_array($d['yest_visits'])) {
    $allVisits = array_merge($allVisits, $d['yest_visits']);
}
if (isset($d['day_before_visits']) && is_array($d['day_before_visits'])) {
    $allVisits = array_merge($allVisits, $d['day_before_visits']);
}
if (isset($d['history']) && is_array($d['history'])) {
    foreach ($d['history'] as $date => $dayData) {
        if (isset($dayData['visits']) && is_array($dayData['visits'])) {
            $allVisits = array_merge($allVisits, $dayData['visits']);
        }
    }
}

// 统计每个IP的访问次数（按时间正序，用于确定"访问序号"）
$ipVisitOrder = [];
$ipVisitCounter = [];
// 先按时间正序排序
usort($allVisits, function($a, $b) {
    return strcmp($a['time'], $b['time']);
});
foreach ($allVisits as $idx => $visit) {
    $ip = $visit['ip'];
    if (!isset($ipVisitCounter[$ip])) {
        $ipVisitCounter[$ip] = 1;
    } else {
        $ipVisitCounter[$ip]++;
    }
    $ipVisitOrder[$ip . '|' . $visit['time']] = $ipVisitCounter[$ip]; // 记录每条记录的访问序号
}

// --- 辅助函数：数据排序与过滤 ---
function processData($rawData, $search, $filter, $sort) {
    $list = [];
    
    if (!empty($rawData) && is_array($rawData)) {
        foreach ($rawData as $v) {
            // 搜索匹配 (IP 或 时间)
            $match = true;
            if (!empty($search)) {
                $ip = $v['ip'] ?? '';
                $time = $v['time'] ?? '';
                if (strpos($ip, $search) === false && strpos($time, $search) === false) {
                    $match = false;
                }
            }
            
            if ($match) {
                $list[] = $v;
            }
        }
    }
    
    // 按时间排序
    if ($sort === 'desc') {
        usort($list, function($a, $b) {
            return strcmp($b['time'], $a['time']);
        });
    } else {
        usort($list, function($a, $b) {
            return strcmp($a['time'], $b['time']);
        });
    }
    
    return $list;
}

// --- 辅助函数：生成表格 ---
function showTable($title, $rawData, $search, $filter, $sort, $ipVisitOrder) {
    echo "<div class='section-header'>
        <h3>$title</h3>
        <div class='buttons'>
            <button class='sort-btn" . ($sort == 'desc' ? ' active' : '') . "' onclick='window.location.href=\"" . buildUrl(['sort' => 'desc']) . "\"'>📅 倒序</button>
            <button class='sort-btn" . ($sort == 'asc' ? ' active' : '') . "' onclick='window.location.href=\"" . buildUrl(['sort' => 'asc']) . "\"'>📅 正序</button>
        </div>
    </div>";
    
    $list = processData($rawData, $search, $filter, $sort);
    
    // 用于临时记录每个IP在当前列表里出现的次数
    $ipCounter = [];
    
    if (!empty($list)) {
        echo "<table><tr><th>排序序号</th><th>访问序号</th><th>IP地址</th><th>访问时间 (累计次数)</th><th>是否新增</th></tr>";
        
        $index = 1;
        foreach ($list as $v) {
            $ip = $v['ip'];
            
            // 过滤：只看新增/只看回头
            if ($filter === 'new') {
                // 该IP在当前列表中是第几次出现？
                $thisCount = isset($ipCounter[$ip]) ? $ipCounter[$ip] + 1 : 1;
                if ($thisCount > 1) {
                    continue; // 不是第1次，跳过
                }
            } else if ($filter === 'old') {
                $thisCount = isset($ipCounter[$ip]) ? $ipCounter[$ip] + 1 : 1;
                if ($thisCount === 1) {
                    continue; // 是第1次，跳过
                }
            }
            
            // 计算该IP在当前列表中是第几次出现
            if (!isset($ipCounter[$ip])) {
                $ipCounter[$ip] = 1;
            } else {
                $ipCounter[$ip]++;
            }
            $currentCount = $ipCounter[$ip];
            
            // 判断是否新增：第1次出现显示新增，第2次及以上显示回头
            $isAbsolutelyNew = ($currentCount === 1);
            
            $status = $isAbsolutelyNew ? '✅ 最新' : '🔄 回头';
            $class = $isAbsolutelyNew ? 'new' : 'old';
            
            $countLabel = " (第 {$currentCount} 次访问)";
            
            // 获取访问序号（该IP在整个历史中的第几次访问）
            $visitOrder = $ipVisitOrder[$ip . '|' . $v['time']] ?? '-';
            
            // 输出IP行，增加归属地占位符
            // 修复了此处：使用单引号包裹JS代码，并正确拼接变量，避免解析中文错误
            echo "<tr><td>{$index}</td>
                      <td>{$visitOrder}</td>
                      <td class='ip-cell'>
                          <strong>{$ip}</strong>
                          <span class='loading-loc' id='loc-{$index}'>查询归属地中...</span>
                      </td>
                      <td>{$v['time']}<span style='color:#666;font-size:12px;margin-left:5px;'>{$countLabel}</span></td>
                      <td class='$class'>$status</td>
                  </tr>
                  <script>
                    fetch('http://ip-api.com/json/" . $ip . "?lang=zh-CN')
                        .then(response => response.json())
                        .then(data => {
                            var locEl = document.getElementById('loc-{$index}');
                            if(data.status === 'success') {
                                var country = data.country || '';
                                var region = data.regionName || '';
                                var city = data.city || '';
                                var fullLoc = country + region + city;
                                locEl.innerText = fullLoc;
                                locEl.className = 'location-text';
                            } else {
                                locEl.innerText = '未知地区';
                                locEl.className = 'location-text';
                            }
                        })
                        .catch(err => {
                            document.getElementById('loc-{$index}').innerText = '查询失败';
                        });
                  </script>";
            $index++;
        }
        echo "</table>";
    } else {
        echo "<p>暂无数据</p>";
    }
}

// 显示今日
showTable("📅 今日访问明细", $d['today_visits'] ?? [], $search, $filter, $sort, $ipVisitOrder);

// 显示昨日
showTable("📅 昨日访问明细", $d['yest_visits'] ?? [], $search, $filter, $sort, $ipVisitOrder);

// 显示前天
showTable("📅 前天访问明细", $d['day_before_visits'] ?? [], $search, $filter, $sort, $ipVisitOrder);

// === 总访问明细 ===
echo "<div class='total-section'>";
showTable("🌐 总访问明细 (含历史所有记录)", $allVisits, $search, $filter, $sort, $ipVisitOrder);
echo "</div>";

echo "<script>
function doSearch() {
    var val = document.getElementById('searchInput').value;
    window.location.href = '" . buildUrl(['search' => 'PLACEHOLDER']) . "'.replace('PLACEHOLDER', encodeURIComponent(val));
}
function clearSearch() {
    window.location.href = '" . buildUrl(['search' => '', 'filter' => '', 'sort' => 'desc']) . "';
}
</script>
    </div>
</body>
</html>";
