<?php
/**
 * 屏蔽模式：GeoIP 国家判定（本地 MaxMind + 30 天 IP 缓存）
 *
 * 依赖全局：$v_info, $reason, $__cloak_debug_on
 */
if (!defined('SHOW_SITE_MODE_SWITCH') || SHOW_SITE_MODE_SWITCH !== 'ip_check') {
    return;
}
if (!defined('CLOAK_GEOIP_ENABLED') || strtoupper(CLOAK_GEOIP_ENABLED) !== 'ON') {
    return;
}
if (!empty($_SESSION['check_result'])) {
    return;
}

$ip = ClientIpResolver::resolve();
if ($ip !== '' && $ip !== '0.0.0.0') {
    $v_info->v_ip = $ip;
    $_SESSION['gcu_ip'] = $ip;
}

$geoMeta = GeoIpCountryResolver::resolveWithMeta($ip);
$countryCode = $geoMeta['code'];
$geoSource   = $geoMeta['source'];

if ($countryCode !== null && $countryCode !== '') {
    $v_info->v_country = $countryCode;
    $_SESSION['gcu_country'] = $countryCode;
}

$allowlist = CountryAllowlist::parse(defined('SHOW_SITE_COUNTRY') ? SHOW_SITE_COUNTRY : '');
if (!CountryAllowlist::isAllowed($countryCode, $allowlist)) {
    $_SESSION['check_result'] = 'false';
    if ($countryCode === null || $countryCode === '') {
        $reason = '无法识别访客国家';
    } else {
        $reason = '国家不符：' . $countryCode;
    }
    if (!empty($GLOBALS['__cloak_debug_on'])) {
        cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'fail', $reason, [
            'ip'         => $ip,
            'country'    => $countryCode,
            'allowlist'  => $allowlist,
            'geo_source' => $geoSource,
        ]);
        cloak_dbg_record(__LINE__, 'false', $reason, ['stage' => 'geoip_country']);
    }
    return;
}

if (!empty($GLOBALS['__cloak_debug_on'])) {
    cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'pass', '国家允许或列表为空', [
        'ip'         => $ip,
        'country'    => $countryCode,
        'allowlist'  => $allowlist,
        'geo_source' => $geoSource,
    ]);
}
