<?php
    // 黑白名单（完整判定链内）：链接参数白名单 > IP 白名单 > 黑名单
    $reason = $reason ?? '';

    if (WhitelistGate::matchesWhitelistParams()) {
        $_SESSION['check_result'] = 'true';
        $reason = '白名单链接参数';
        if ($__cloak_debug_on) {
            cloak_dbg_step(__LINE__, '链接参数白名单', 'pass', defined('WHITE_PARAMS') ? WHITE_PARAMS : '');
            cloak_dbg_record(__LINE__, 'true', $reason, ['stage' => 'whitelist_params']);
        }
        return;
    }

    if (WhitelistGate::matchesWhitelistIp(WhitelistGate::resolveVisitorIp($v_info))) {
        $_SESSION['check_result'] = 'true';
        $reason = '白名单';
        if ($__cloak_debug_on) {
            cloak_dbg_step(__LINE__, 'IP 白名单', 'pass', 'IP 在白名单组/列表中');
            cloak_dbg_record(__LINE__, 'true', $reason, ['stage' => 'whitelist_ip']);
        }
        return;
    }

    if ($__cloak_debug_on && defined('WHITE_PARAMS') && WHITE_PARAMS !== '') {
        cloak_dbg_step(__LINE__, '链接参数白名单', 'skip', '参数不匹配: ' . WHITE_PARAMS);
    }

    $match = false;
    if (defined('BLACKLIST_GROUP_ID') && (int) BLACKLIST_GROUP_ID > 0) {
        $blEntries = ip_group_list_addresses((int) BLACKLIST_GROUP_ID);
        $match     = ip_visitor_in_blacklist_entries($v_info->v_ip, $blEntries);
    }
    if ($__cloak_debug_on) {
        cloak_dbg_step(__LINE__, '黑名单检查', $match ? 'fail' : 'pass', $match ? 'IP 在黑名单组内' : '未命中黑名单', [
            'ip'       => $v_info->v_ip,
            'group_id' => defined('BLACKLIST_GROUP_ID') ? BLACKLIST_GROUP_ID : 0,
        ]);
    }
    if ($match) {
        $_SESSION['check_result'] = 'false';
        $reason = '黑名单';
        if ($__cloak_debug_on) {
            cloak_dbg_record(__LINE__, 'false', $reason, ['stage' => 'blacklist']);
        }
    }
