<?php
/**
 * 日志大字段按需加载（fp_hdata、api_* 等）
 */
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;
$field = isset($_GET['field']) ? (string) $_GET['field'] : '';

$allowed = [
    'fp_hdata'          => 'fp_hdata',
    'api_by_request'    => 'api_by_request',
    'api_by_response'   => 'api_by_response',
    'api_risk_request'  => 'api_risk_request',
    'api_risk_response' => 'api_risk_response',
    'user_agent'        => 'user_agent',
    'http_referer'      => 'http_referer',
    'accept_language_raw' => 'accept_language_raw',
];

if ($id <= 0 || !isset($allowed[$field])) {
    echo json_encode(['code' => 1, 'msg' => 'invalid request']);
    exit;
}

$col = $allowed[$field];
$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 `' . $col . '` AS `blob` FROM `visitor_logs` WHERE `id`=' . $id . ' LIMIT 1';
$res = $conn->query($sql);
$row = $res ? $res->fetch_assoc() : null;
if ($res) {
    $res->free();
}
$conn->close();

$blob = trim((string) ($row['blob'] ?? ''));
if ($blob === '') {
    echo json_encode(['code' => 1, 'msg' => 'empty']);
    exit;
}

echo json_encode([
    'code'  => 0,
    'msg'   => '',
    'field' => $field,
    'data'  => $blob,
], JSON_UNESCAPED_UNICODE);
