<?php
/**
 * 二次风控判定解析（按需加载，供日志列表点击「判定详情」）
 */
require_once dirname(__DIR__) . '/cong.php';
require_once dirname(__DIR__) . '/lib/DbHelper.php';
require_once dirname(__DIR__) . '/datatable/auth.php';

cloak_datatable_require_auth();

header('Content-Type: application/json; charset=utf-8');

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($id <= 0) {
    echo json_encode(['code' => 1, 'msg' => 'invalid id']);
    exit;
}

$conn = new mysqli('localhost', DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
    echo json_encode(['code' => 1, 'msg' => 'db error']);
    exit;
}

$sql = "SELECT `id`, `fp_hdata`, `reason`, `result`, `domain` FROM `visitor_logs` WHERE `id`=" . $id . ' LIMIT 1';
$res = $conn->query($sql);
$row = $res ? $res->fetch_assoc() : null;
if ($res) {
    $res->free();
}
$conn->close();

if (!$row || empty($row['fp_hdata'])) {
    echo json_encode(['code' => 1, 'msg' => 'no fp_hdata']);
    exit;
}

$result = $row['result'] ?? '';
if ($result === 'wait') {
    $result = '检测中';
}

$explain = cloak_visitor_log_fp_risk_explain(
    $row['fp_hdata'],
    $row['reason'] ?? '',
    $result,
    $row['domain'] ?? ''
);

echo json_encode([
    'code'    => 0,
    'msg'     => '',
    'summary' => $explain['summary'],
    'html'    => $explain['html'],
], JSON_UNESCAPED_UNICODE);
