<?php
/**
 * IP 查询接口
 * 支持 ?ip=1.1.1.1
 * 返回 JSON 格式：
 * {"country":"中国","province":"湖南","city":"长沙"}
 */

header('Content-Type: application/json; charset=utf-8');
error_reporting(0);

require_once __DIR__ . '/geoip/vendor/autoload.php'; // 注意 vendor 路径
use GeoIp2\Database\Reader;

$ip = isset($_GET['ip']) ? $_GET['ip'] : $_SERVER['REMOTE_ADDR'];

// 简单校验 IP
if(!filter_var($ip, FILTER_VALIDATE_IP)){
    echo json_encode(['error'=>'请输入正确 IP']);
    exit;
}

try {
    // GeoLite2 数据库路径
    $reader = new Reader(__DIR__ . '/geoip/GeoLite2-City.mmdb');

    $record = $reader->city($ip);

    $country  = $record->country->names['zh-CN'] ?? $record->country->name ?? '';
    $province = $record->mostSpecificSubdivision->names['zh-CN'] ?? $record->mostSpecificSubdivision->name ?? '';
    $city     = $record->city->names['zh-CN'] ?? $record->city->name ?? '';

    // 国内显示市
    if($country === '中国'){
        $city_name = $city ?: $province;
    } else {
        // 国外显示州/省，如果没有州显示国家
        $city_name = $province ?: $country;
    }

    echo json_encode([
        'country'  => $country,
        'province' => $province,
        'city'     => $city_name
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e){
    echo json_encode([
        'country' => '未知',
        'province'=> '',
        'city'    => '未知'
    ], JSON_UNESCAPED_UNICODE);
}
