<?php
require_once(dirname(__DIR__) . "/datatable/countries.php");
require_once(dirname(__DIR__) . "/cong.php");
require_once(dirname(__DIR__) . "/lib/DbHelper.php");
require_once(dirname(__DIR__) . "/lib/Cloak/PipelineTimer.php");
require_once(dirname(__DIR__) . "/lib/Cloak/VisitorLogSchema.php");
require_once(dirname(__DIR__) . "/lib/Cloak/VisitorApiAudit.php");

$reasons = array(
    "blank_referrer" => "过滤无来源的访问",
    "blacklisted_ptr" =>    "过滤黑名单主机名的访问者",
    "proxy" =>  "   过滤代理和VPN",
    "filter_isps" =>    "过滤不常见的服务提供商",
    "switched_browsers" =>  "过滤多少分钟内切换浏览器",
    "invalid_google_click_id" =>    "必须是有效的googleID",
    "non_touch_device" =>   "过滤非接触设备",
    "spoofed_browser" =>    "过滤浏览器欺骗设备",
    "sticky_filtering" =>   "启用粘贴过滤",
    "whitelisted_browser_ids" =>    "可访问的用户ID",
    "blacklisted_browser_ids" =>    "不可访问的用户ID",
    "whitelisted_urlrules" =>   "白名单链接参数",
    "blacklisted_urlrules" =>   "黑名单链接参数",
    "device_desktop" => "过滤电脑访问",
    "device_mobile" =>  "过滤手机的访问",
    "device_tablet" =>  "过滤平板的访问",
    "device_no_accel" =>    "过滤没有加速度计/陀螺仪的设备",
    "device_headless_browser" => "过滤没有浏览器头的访问",
    "isp_type" =>   "过滤指定的ISP类型",
    "browser_time_zone" =>  "可以访问的浏览器时区",
    "whitelisted_language_codes" => "允许访问的浏览器语言",
    "blacklisted_language_codes" => "不允许访问的浏览器语言",
    "agent" =>  "代理商列表",
    "ip_lists" => "IP列表",
    "referrer" =>   "来源用户列表",
    "org" =>    "组织机构列表",
    "deadbolt" =>   "是否限制访问",
    "global_db" =>  "全球IP数据库",
    "org_isp" =>    "组织或者ISP",
    "cross_campaign_ip_visits" =>   "每个IP最多可访问多少个",
    "too_many_ip_visits" => "每个IP最多可访问多少次",
    "too_many_browser_visits" =>    "每个浏览器最多可访问多少次",
    "whitelisted_safe_page_url" =>  "仅允许页面地址包含",
    "blacklisted_safe_page_url" =>  "过滤页面地址包含",
    "time_of_day" =>    "不可访问的日期",
);

$servername = "localhost";
$username = DB_USERNAME;
$password = DB_PASSWORD;
$dbname = DB_NAME;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$jsonResult = array();
// Check connection
if ($conn->connect_error) {
    $error = "Connection failed: " . $conn->connect_error;
    $handle = fopen(dirname(__FILE__) . "/err.txt", "a+");
    fwrite($handle, date("Y-m-d H:i:s") . ' | ' . $error . "\n");
    fclose($handle);

    $jsonResult["code"] = 1;
    $jsonResult["msg"] = $error;
    $jsonResult["count"] = 0;
    $jsonResult["data"] = array();
} else {
    VisitorLogSchema::ensureColumns($conn);
    if(isset($_GET['clear']) && $_GET['clear'] == "true") { //清除日志数据表
        $sql = "TRUNCATE `visitor_logs`";
         
        // 执行查询并输出结果
        $result = mysqli_query($conn, $sql);
        $jsonResult["code"] = 0;
        $jsonResult["msg"] = "success";
        $jsonResult["count"] = 0;
        $jsonResult["data"] = array();
    } else {    // 默认分页数据
        // 获取当前页码（默认为第1页）
        $pageNumber = isset($_GET['page']) ? (int) $_GET['page'] : 1;
         
        // 设置每页显示的记录条数
        $recordsPerPage = isset($_GET['limit']) ? (int) $_GET['limit'] : 50;
         
        // 计算起始位置
        $startPosition = ($pageNumber - 1) * $recordsPerPage;
        $map = array();
        $where = 1;
        
        if(!empty($_GET['visit_date'])) {
            $map[] = "DATE_FORMAT(`visit_date`, '%Y-%m-%d') LIKE '" . cloak_db_escape($conn, $_GET['visit_date']) . "'";
        }

        $where .= cloak_visitor_log_apply_result_filter($conn, $_GET['result'] ?? '');
        
        if(!empty($_GET['country'])) {
            $map[] = "country LIKE '" . cloak_db_escape($conn, $_GET['country']) . "'";
        }
        
        if(!empty($_GET['IP'])) {
            $map[] = "IP LIKE '" . cloak_db_escape($conn, $_GET['IP']) . "'";
        }
        
        if(!empty($_GET['domain'])) {
            $map[] = "domain LIKE '%" . cloak_db_escape($conn, $_GET['domain']) . "%'";
        }
        
        if(!empty($_GET['spage'])) {
            $map[] = "page LIKE '%" . cloak_db_escape($conn, $_GET['spage']) . "%'";
        }
        
        if(!empty($map)) {
            $where .= " AND " . join(" AND ", $map);
        }
        // SQL语句
        $sql = "SELECT `id`, `campagin_id`, `visit_md5_code`, `domain`, `visit_date`, `IP`, `country`, `result`, `reason`, `fp_url`, `referer`, `vtimes`, `client`, `browser`, `page`, `language`, `user_agent`, `http_referer`, `accept_language_raw`, `judge_timing`, `fp_hdata`, `api_by_request`, `api_by_response`, `api_risk_request`, `api_risk_response`, `device`, `add_time` FROM `visitor_logs` WHERE {$where} ORDER BY `id` DESC LIMIT {$startPosition}, {$recordsPerPage}";
         
        // 执行查询并输出结果
        $result = mysqli_query($conn, $sql);
        $jsonData = array();
    
        while ($row = mysqli_fetch_assoc($result)) {
            //echo "<p>{$row["columnName"]}</p>"; // 根据需要修改列名
            if($row['vtimes'] == 0) {
                $row['vtimes'] = 1;             // 还未统计访问次数
                $sqlVtimes = mysqli_query($conn, "SELECT count(*) as `total` FROM `visitor_logs` WHERE `IP` = '" . cloak_db_escape($conn, $row["IP"]) . "' AND `domain` = '" . cloak_db_escape($conn, $row["domain"]) . "' AND id < " . (int)$row['id']);
                $vtimesRow = mysqli_fetch_assoc($sqlVtimes);
                $vtimes = $vtimesRow["total"];  // 如果之前此IP有访问记录
                if($vtimes > 0) {
                    $row['vtimes'] += $vtimes;  // 访问次数叠加
                }
                
                // 更新访问次数
                $updateSql = "UPDATE `visitor_logs` SET `vtimes`=" . (int)$row['vtimes'] . " WHERE id = " . $row['id'];
                mysqli_query($conn, $updateSql);
            }
            
            $row['country'] = $countries[$row['country']];
            if(isset($reasons[$row['reason']])) {
                $row['reason'] = $reasons[$row['reason']];
            }
            if ($row['result'] === 'wait') {
                $row['result'] = '检测中';
            }
            $row['judge_timing_text'] = cloak_visitor_log_format_timing($row['judge_timing'] ?? '');
            $row['fp_hdata_text'] = cloak_visitor_log_format_fp_hdata($row['fp_hdata'] ?? '');
            if (!empty($row['fp_hdata'])) {
                $explain = cloak_visitor_log_fp_risk_explain(
                    $row['fp_hdata'],
                    $row['reason'] ?? '',
                    $row['result'] ?? '',
                    $row['domain'] ?? ''
                );
                $row['fp_hdata_explain_summary'] = $explain['summary'];
                $row['fp_hdata_explain_html']    = $explain['html'];
                $row['fp_hdata_explain']         = $explain['data'];
            } else {
                $row['fp_hdata_explain_summary'] = '';
                $row['fp_hdata_explain_html']    = '';
                $row['fp_hdata_explain']         = null;
            }
            $row['api_by_request_text']   = VisitorApiAudit::displayText($row['api_by_request'] ?? '');
            $row['api_by_response_text']  = VisitorApiAudit::displayText($row['api_by_response'] ?? '');
            $row['api_risk_request_text'] = VisitorApiAudit::displayText($row['api_risk_request'] ?? '');
            $row['api_risk_response_text']= VisitorApiAudit::displayText($row['api_risk_response'] ?? '');
            $jsonData[] = $row;
        }
    
        $sqlCount = mysqli_query($conn, "SELECT count(*) as `total` FROM `visitor_logs` WHERE {$where}");
        $countRow = mysqli_fetch_assoc($sqlCount);
    
        $jsonResult["code"] = 0;
        $jsonResult["msg"] = "";
        $jsonResult["count"] = $countRow['total'];
        $jsonResult["data"] = $jsonData;
    }
}
 
// 关闭数据库连接
mysqli_close($conn);

header('Content-Type: application/json');

echo json_encode($jsonResult);exit;
