<?php
/**
 * 流量统计收集脚本
 * 定时任务：每天凌晨执行，收集用户网站流量数据
 * 
 * 使用方法：
 * 1. 手动执行：php cron/collect_traffic.php
 * 2. 宝塔定时任务：每天凌晨0点执行
 * 
 * 流量数据来源：
 * 1. 首先尝试通过宝塔监控插件(monitor)的API获取详细数据
 * 2. 如果失败，尝试通过宝塔站点API获取
 */

require_once __DIR__ . '/../MPHX/common.php';

// 获取数据库连接
global $DB;

// 获取所有有网站的用户
$users = $DB->query("SELECT z.*, b.ip as bt_ip, b.dk as bt_port, b.key as bt_key, b.aqfw 
    FROM `zj` z 
    LEFT JOIN `bt` b ON z.btid = b.id 
    WHERE z.zt = '正常'");

$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$collected = 0;
$errors = 0;

echo "[" . date('Y-m-d H:i:s') . "] 开始收集流量数据...\n";

while ($user = $DB->fetch($users)) {
    if (empty($user['btid']) || empty($user['webid'])) {
        continue;
    }
    
    // 初始化宝塔API
    $protocol = isset($user['aqfw']) && $user['aqfw'] == 'true' ? 'https' : 'http';
    $bt_api = new bt_api();
    $bt_api->BT_PANEL = $protocol . '://' . $user['bt_ip'] . ':' . $user['bt_port'];
    $bt_api->BT_KEY = $user['bt_key'];
    
    // 默认值
    $traffic_in = 0;
    $traffic_out = 0;
    $traffic_total = 0;
    $request_count = 0;
    $pv_number = 0;
    $uv_number = 0;
    $ip_number = 0;
    $method_get = 0;
    $method_post = 0;
    $pc_count = 0;
    $mobile_count = 0;
    $spider_count = 0;
    $gzip_count = 0;
    $slow_count = 0;
    $status_200 = 0;
    $status_404 = 0;
    $status_500 = 0;
    
    // 获取网站名称
    $site_name = $user['user'];
    
    // 方法1：使用宝塔监控插件(monitor)的API获取详细流量数据
    $monitor_data = $bt_api->getMonitorGlobalTotal($site_name, $yesterday, $today);
    
    if ($monitor_data && isset($monitor_data['recv_bytes'])) {
        $traffic_in = intval($monitor_data['recv_bytes']);  // 接收字节 = 入站
        $traffic_out = intval($monitor_data['sent_bytes']); // 发送字节 = 出站
        $traffic_total = $traffic_in + $traffic_out;
        $request_count = intval($monitor_data['request']);
        $pv_number = intval($monitor_data['pv_number']);
        $uv_number = intval($monitor_data['uv_number']);
        $ip_number = intval($monitor_data['ip_number']);
        $method_get = intval($monitor_data['method_get']);
        $method_post = intval($monitor_data['method_post']);
        $pc_count = intval($monitor_data['pc_count']);
        $mobile_count = intval($monitor_data['mobile_count']);
        $spider_count = intval($monitor_data['spider_count']);
        $gzip_count = intval($monitor_data['gzip']);
        $slow_count = intval($monitor_data['slow_count']);
        $status_200 = intval($monitor_data['status_200']);
        $status_404 = intval($monitor_data['status_404']);
        $status_500 = intval($monitor_data['status_500']);
        
        echo "[" . date('Y-m-d H:i:s') . "] 用户 {$user['user']}: 通过monitor插件获取详细流量数据 - 总流量 {$traffic_total} 字节, PV: {$pv_number}, UV: {$uv_number}\n";
    } else {
        // 方法2：使用宝塔监控插件的单日API获取基本流量数据
        $day_data = $bt_api->getMonitorTraffic($site_name, $today);
        
        if ($day_data && isset($day_data['recv_bytes'])) {
            $traffic_in = intval($day_data['recv_bytes']);
            $traffic_out = intval($day_data['sent_bytes']);
            $traffic_total = $traffic_in + $traffic_out;
            $request_count = intval($day_data['request']);
            $pv_number = intval($day_data['pv_number']);
            $uv_number = intval($day_data['uv_number']);
            $ip_number = intval($day_data['ip_number']);
            
            echo "[" . date('Y-m-d H:i:s') . "] 用户 {$user['user']}: 通过monitor插件单日API获取流量 - 总流量 {$traffic_total} 字节\n";
        } else {
            // 方法3：使用宝塔站点API获取实时流量
            $site_traffic = $bt_api->GetSiteTraffic($user['webid']);
            if ($site_traffic && isset($site_traffic['status']) && $site_traffic['status']) {
                $traffic_in = isset($site_traffic['down']) ? intval($site_traffic['down']) : 0;
                $traffic_out = isset($site_traffic['up']) ? intval($site_traffic['up']) : 0;
                $traffic_total = $traffic_in + $traffic_out;
                
                echo "[" . date('Y-m-d H:i:s') . "] 用户 {$user['user']}: 通过站点API获取流量 - 入站 {$traffic_in} 字节, 出站 {$traffic_out} 字节\n";
            }
        }
    }
    
    // 如果获取到流量数据，保存到数据库
    if ($traffic_total > 0 || $traffic_in > 0 || $traffic_out > 0) {
        if ($traffic_total > 0 && $traffic_in == 0 && $traffic_out == 0) {
            // 只有总流量时，假设入站和出站各占一半
            $traffic_in = intval($traffic_total / 2);
            $traffic_out = $traffic_total - $traffic_in;
        }
        
        if ($traffic_total == 0) {
            $traffic_total = $traffic_in + $traffic_out;
        }
        
        // 检查是否已有记录
        $existing = $DB->get_row("SELECT id FROM `traffic_stats` WHERE user_id='{$user['id']}' AND stat_date='{$today}'");
        
        if ($existing) {
            // 更新记录
            $DB->query("UPDATE `traffic_stats` SET 
                traffic_in = '{$traffic_in}', 
                traffic_out = '{$traffic_out}', 
                traffic_total = '{$traffic_total}',
                request_count = '{$request_count}',
                pv_number = '{$pv_number}',
                uv_number = '{$uv_number}',
                ip_number = '{$ip_number}',
                method_get = '{$method_get}',
                method_post = '{$method_post}',
                pc_count = '{$pc_count}',
                mobile_count = '{$mobile_count}',
                spider_count = '{$spider_count}',
                gzip_count = '{$gzip_count}',
                slow_count = '{$slow_count}',
                status_200 = '{$status_200}',
                status_404 = '{$status_404}',
                status_500 = '{$status_500}',
                web_id = '{$user['webid']}'
                WHERE user_id='{$user['id']}' AND stat_date='{$today}'");
        } else {
            // 插入新记录
            $DB->query("INSERT INTO `traffic_stats` 
                (user_id, bt_id, web_id, stat_date, traffic_in, traffic_out, traffic_total, 
                request_count, pv_number, uv_number, ip_number, method_get, method_post, 
                pc_count, mobile_count, spider_count, gzip_count, slow_count, 
                status_200, status_404, status_500) 
                VALUES 
                ('{$user['id']}', '{$user['btid']}', '{$user['webid']}', '{$today}', 
                '{$traffic_in}', '{$traffic_out}', '{$traffic_total}',
                '{$request_count}', '{$pv_number}', '{$uv_number}', '{$ip_number}', 
                '{$method_get}', '{$method_post}', '{$pc_count}', '{$mobile_count}', 
                '{$spider_count}', '{$gzip_count}', '{$slow_count}',
                '{$status_200}', '{$status_404}', '{$status_500}')");
        }
        
        $collected++;
        echo "[" . date('Y-m-d H:i:s') . "] 用户 {$user['user']}: 今日流量 {$traffic_total} 字节 (入: {$traffic_in}, 出: {$traffic_out}) [PV: {$pv_number}, UV: {$uv_number}]\n";
    } else {
        // 无法获取流量数据
        echo "[" . date('Y-m-d H:i:s') . "] 用户 {$user['user']}: 无法获取流量数据\n";
        $errors++;
    }
}

echo "[" . date('Y-m-d H:i:s') . "] 流量收集完成：收集 {$collected} 条记录，失败 {$errors} 条\n";

// 清理90天前的旧数据
$cleanup_date = date('Y-m-d', strtotime('-90 days'));
$deleted = $DB->query("DELETE FROM `traffic_stats` WHERE stat_date < '{$cleanup_date}'");
echo "[" . date('Y-m-d H:i:s') . "] 清理旧数据：删除 {$deleted} 条90天前的记录\n";
