<?php
/*
 * 追风科学院 404 页 - 服务端信息端点
 * 提供：客户端公网 IP、IP 来源、地理位置（省/市/运营商）、服务端时间
 * 部署位置：static.zhuifeng.org 的 public_html/api/info.php
 * 访问路径：https://static.zhuifeng.org/api/info.php
 */
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Access-Control-Allow-Origin: *');

$ip = '';
$source = '';
if (!empty($_SERVER['HTTP_ALI_REAL_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_ALI_REAL_CLIENT_IP'];
    $source = '阿里云 ESA (ali-real-client-ip)';
} elseif (!empty($_SERVER['HTTP_ALI_CDN_REAL_IP'])) {
    $ip = $_SERVER['HTTP_ALI_CDN_REAL_IP'];
    $source = '阿里云 CDN/DCDN (ali-cdn-real-ip)';
} elseif (!empty($_SERVER['HTTP_TRUE_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_TRUE_CLIENT_IP'];
    $source = 'True-Client-IP';
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $parts = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    $ip = trim($parts[0]);
    $source = 'X-Forwarded-For';
} elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
    $ip = $_SERVER['HTTP_X_REAL_IP'];
    $source = 'X-Real-IP';
} else {
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $source = '服务端直连 (REMOTE_ADDR)';
}

/* ESA 访问者位置标头（国家） */
$country = strtolower($_SERVER['HTTP_ALI_IP_COUNTRY'] ?? '');
$countryNames = array(
    'cn' => '中国内地', 'hk' => '中国香港', 'mo' => '中国澳门', 'tw' => '中国台湾',
    'us' => '美国', 'jp' => '日本', 'kr' => '韩国', 'sg' => '新加坡',
);
$countryName = isset($countryNames[$country]) ? $countryNames[$country] : '';

/* IP 详细地理位置：ip-api.com（免费，中文，服务器端调用） */
$region = '';
$city = '';
$isp = '';
$geoSource = '';

function is_private_ip($ip) {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $parts = explode('.', $ip);
        $first = (int)$parts[0];
        if ($first === 10) return true;
        if ($first === 127) return true;
        if ($first === 172 && (int)$parts[1] >= 16 && (int)$parts[1] <= 31) return true;
        if ($first === 192 && (int)$parts[1] === 168) return true;
        return false;
    }
    return false;
}

if ($ip && !is_private_ip($ip)) {
    $cacheDir = sys_get_temp_dir() . '/zf_geoip';
    if (!is_dir($cacheDir)) @mkdir($cacheDir, 0700, true);
    $cacheFile = $cacheDir . '/' . md5($ip) . '.json';

    $geo = null;
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 86400)) {
        $geo = json_decode(@file_get_contents($cacheFile), true);
        $geoSource = 'ip-api.com（缓存）';
    } else {
        $url = 'http://ip-api.com/json/' . urlencode($ip) . '?lang=zh-CN&fields=status,message,country,regionName,city,isp,query';
        $ch = curl_init($url);
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 3,
            CURLOPT_CONNECTTIMEOUT => 2,
        ));
        $resp = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($resp && $httpCode === 200) {
            $geo = json_decode($resp, true);
            if (($geo['status'] ?? '') === 'success') {
                @file_put_contents($cacheFile, $resp);
                $geoSource = 'ip-api.com';
            } else {
                $geo = null;
            }
        }
    }

    if ($geo && ($geo['status'] ?? '') === 'success') {
        $region = $geo['regionName'] ?? '';
        $city = $geo['city'] ?? '';
        $isp = $geo['isp'] ?? '';
        if (!$countryName && !empty($geo['country'])) {
            $countryName = $geo['country'];
        }
        // ISP 英文名 → 中文
        $ispMap = array(
            'Chinanet' => '中国电信', 'China Telecom' => '中国电信',
            'China Unicom' => '中国联通', 'Unicom' => '中国联通',
            'China Mobile' => '中国移动', 'CMNET' => '中国移动',
            'China Railcom' => '中国铁通', 'China Tietong' => '中国铁通',
            'Tencent' => '腾讯云', 'Alibaba' => '阿里云', 'Aliyun' => '阿里云',
            'Huawei Cloud' => '华为云', 'Baidu' => '百度云',
            'China Education and Research Network Center' => '中国教育和科研计算机网',
            'CERNET' => '中国教育和科研计算机网',
            'China Science and Technology Network' => '中国科技网',
            'Asia Pacific Network Information Centre' => 'APNIC',
        );
        $ispRaw = $isp;
        foreach ($ispMap as $en => $zh) {
            if (stripos($isp, $en) !== false) { $isp = $zh; break; }
        }
        // 兜底：含关键词的模糊匹配
        if ($isp === $ispRaw) {
            if (preg_match('/telecom|chinanet/i', $isp)) $isp = '中国电信';
            elseif (preg_match('/unicom|cnc/i', $isp)) $isp = '中国联通';
            elseif (preg_match('/mobile|cmcc/i', $isp)) $isp = '中国移动';
            elseif (preg_match('/tietong|railcom/i', $isp)) $isp = '中国铁通';
            elseif (preg_match('/cernet|education/i', $isp)) $isp = '教育网';
        }
        // 城市/省份若为纯拼音（ip-api 小地名偶发），标注原文，不强行翻译
        if ($city && preg_match('/^[A-Za-z\s\.\-]+$/', $city)) {
            $city = $city . '（音译）';
        }
        if ($region && preg_match('/^[A-Za-z\s\.\-]+$/', $region)) {
            $region = $region . '（音译）';
        }
    }
}

$location = trim(($countryName ?: '') . ' ' . ($region ?: '') . ' ' . ($city ?: ''));
if (!$location) $location = '—';

echo json_encode(array(
    'ip'           => $ip,
    'ip_source'    => $source,
    'server_time'  => gmdate('Y-m-d H:i:s') . ' UTC',
    'country'      => $country,
    'country_name' => $countryName,
    'region'       => $region,
    'city'         => $city,
    'isp'          => $isp,
    'location'     => $location,
    'geo_source'   => $geoSource,
), JSON_UNESCAPED_UNICODE);
