<?php
/**==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==**/
/**
 * 客户端指纹信息风险评估处理器
 * 接收前端发送的指纹数据并进行综合风险判断
 */
session_start();
// 设置响应头为JSON格式
header('Content-Type: application/json; charset=utf-8');

// 确保请求方法为POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'status' => 'error',
        'message' => '只允许POST请求'
    ]);
    exit;
}

// 获取并解析请求数据
$hdata = $_POST['hdata'] ?? '';
$decodedString = base64_decode($hdata, true);
$fingerprint_info = is_string($decodedString) ? json_decode($decodedString, true) : null;

if (!is_array($fingerprint_info) || empty($fingerprint_info['domain'])) {
    http_response_code(400);
    echo json_encode([
        'status'  => 'error',
        'message' => '无效的指纹数据',
    ]);
    exit;
}

require_once __DIR__ . '/cong.php';
require_once __DIR__ . '/lib/DbHelper.php';
require_once __DIR__ . '/lib/bootstrap.php';
require_once __DIR__ . '/config/ConfigLoader.php';
require_once __DIR__ . '/lib/Cloak/FpUrlHelper.php';

$fp_host = parse_url($fingerprint_info['domain'], PHP_URL_HOST);
if (empty($fp_host)) {
    $fp_host = $_SERVER['HTTP_HOST'] ?? '';
}
$config_name = ConfigLoader::loadByHost($fp_host);

$jsonData = [
    'id'          => COSTM_IP_SCORE,
    'hdata'       => $hdata,
    'referer'     => $fingerprint_info['referer'] ?? '',
    'domain'      => $fingerprint_info['domain'],
    'ip'          => $fingerprint_info['ip'] ?? '',
    'risk_enhanced' => defined('CLOAK_RISK_ENHANCED') && strtoupper(CLOAK_RISK_ENHANCED) === 'ON' ? 1 : 0,
    'risk_number' => CLOAK_RISK_NUMBER,
];

$ch = curl_init('https://www.tiktokba.com/cloak/byApiRisk');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_USERAGENT, get_SERVER_value('HTTP_USER_AGENT'));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-type: application/x-www-form-urlencoded',
    'escloak-key: ' . CHECK_KEY,
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonData));
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'forward_response_cookies');
if ($_COOKIE) {
    curl_setopt($ch, CURLOPT_COOKIE, encode_visitor_cookies());
}
$return = curl_exec($ch);
if ($return === false) {
    http_response_code(502);
    echo json_encode([
        'status'  => 'error',
        'message' => 'Curl error: ' . curl_error($ch),
    ]);
    curl_close($ch);
    exit;
}
curl_close($ch);
$return = json_decode($return, true);
if (!is_array($return)) {
    http_response_code(502);
    echo json_encode([
        'status'  => 'error',
        'message' => '风控 API 返回无效',
    ]);
    exit;
}

$_SESSION['visit_to_3'] = 3;
$response = [];
$response['reason'] = $return['reason'];
$response['result'] = $return['result'];

if($return['result']) {
    $_SESSION["check_result"] = "true";     // 通过指纹参数
    $resolved = FpUrlHelper::resolve($config_name, true);
    $fp_url   = $resolved['url'];
    $response['link'] = $fp_url;
} else {
    $_SESSION["check_result"] = "false";    // 未通过指纹参数
    if(CLOAK_REDIRECT_METHOD == 'curl') {
        $response['link'] = '';
    } else {
        $zp_url = DB_ZP;
        $response['link'] = $zp_url;
    }
}

$log_id = (int) ($fingerprint_info['log_id'] ?? 0);
$update_log = [];

$update_log['result'] = $response['result'] ? "true" : "false";
$update_log['reason'] = $response['reason'] ?? '';
$update_log['fp_url'] = trim((string) ($response['link'] ?? ''));
if ($update_log['fp_url'] === '') {
    $update_log['fp_url'] = $update_log['result'] === 'true'
        ? FpUrlHelper::fallbackUrl()
        : (defined('DB_ZP') ? (string) DB_ZP : '');
}

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// 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);
} elseif ($log_id > 0) {
    $resultEsc = cloak_db_escape($conn, $update_log['result'] ?? '');
    $reasonEsc = cloak_db_escape($conn, strip_tags(cloak_db_string($update_log['reason'] ?? '')));
    $fpUrlEsc  = cloak_db_escape($conn, strip_tags(cloak_db_string($update_log['fp_url'] ?? '')));
    $sql       = "UPDATE `visitor_logs` SET `result`='{$resultEsc}',`reason`='{$reasonEsc}',`fp_url`='{$fpUrlEsc}' WHERE `id`='" . (int) $log_id . "'";

    if ($conn->query($sql) != TRUE) {
        $handle = fopen(dirname(__FILE__) . "/err.txt", "a+");
        fwrite($handle, date("Y-m-d H:i:s") . ' | ' . "Error: " . $sql . "<br>" . $conn->error . "\n");
        fclose($handle);
    }
    $conn->close();
}

// 记录日志
exit(json_encode($response));