<?php
/**
 * 屏蔽模式：GeoIP 国家判定（本地 MaxMind + 30 天 IP 缓存）
 * 未开启国家条件（SHOW_SITE_COUNTRY 为空）时跳过。
 */
require_once __DIR__ . '/../../CountryAllowlist.php';
require_once __DIR__ . '/../../ClientIpResolver.php';
require_once __DIR__ . '/../../GeoIpCountryResolver.php';
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;
}

if (!CountryAllowlist::isEnabled()) {
    if (!empty($GLOBALS['__cloak_debug_on'])) {
        cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'skip', '未开启国家条件，跳过本地 MaxMind 判定');
    }
    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 : '');

// MaxMind 查不到有效国家：跳过本地判定，继续走 byApi（已传 country_code 作兜底）
if ($countryCode === null || $countryCode === '') {
    if (!empty($GLOBALS['__cloak_debug_on'])) {
        cloak_dbg_step(__LINE__, 'GeoIP国家判定', 'skip', 'MaxMind 未识别国家，跳过本地判定，交由 byApi 兜底', [
            'ip'         => $ip,
            'allowlist'  => $allowlist,
            'geo_source' => $geoSource,
        ]);
    }
    return;
}

if (!CountryAllowlist::isAllowed($countryCode, $allowlist)) {
    $_SESSION['check_result'] = 'false';
    $reason = '国家不符：访客 ' . $countryCode;
    if ($allowlist !== []) {
        $reason .= '，允许 ' . implode(',', $allowlist);
    }
    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,
    ]);
}
