<?php
     $file = 'counter.dat';

// 读取并自增
$counter = (int)@file_get_contents($file);
$counter++;

// 使用 LOCK_EX 防止并发写入冲突
file_put_contents($file, $counter, LOCK_EX); 
 ?>
<?php
// IP Geolocation API

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// Get IP from URL parameter or use visitor's IP
$ip = $_GET['ip'] ?? $_SERVER['REMOTE_ADDR'];

// Validate IP address
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'code' => 400,
        'message' => 'Invalid IP address',
        'ip' => $ip
    ]);
    exit;
}

// Try multiple IP geolocation services for better reliability
$result = null;
$error = null;

// Method 1: Use ip.sb API
$url1 = "https://api.ip.sb/geoip/" . urlencode($ip);
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url1);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_TIMEOUT, 5);
curl_setopt($ch1, CURLOPT_USERAGENT, 'Mozilla/5.0');
$response1 = curl_exec($ch1);
$http_code1 = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
curl_close($ch1);

if ($http_code1 == 200 && $response1) {
    $data1 = json_decode($response1, true);
    if ($data1 && isset($data1['ip'])) {
        $result = [
            'status' => 'success',
            'code' => 200,
            'ip' => $data1['ip'],
            'country' => $data1['country'] ?? 'Unknown',
            'country_code' => $data1['country_code'] ?? null,
            'city' => $data1['city'] ?? 'Unknown',
            'region' => $data1['region'] ?? 'Unknown',
            'latitude' => $data1['latitude'] ?? null,
            'longitude' => $data1['longitude'] ?? null,
            'isp' => $data1['isp'] ?? 'Unknown',
            'timezone' => $data1['timezone'] ?? null,
            'asn' => $data1['asn'] ?? null,
            'organization' => $data1['organization'] ?? null,
            'type' => $data1['type'] ?? 'Unknown'
        ];
    }
}

// Method 2: Fallback to ipapi.co if Method 1 fails
if (!$result) {
    $url2 = "https://ipapi.co/" . urlencode($ip) . "/json/";
    $ch2 = curl_init();
    curl_setopt($ch2, CURLOPT_URL, $url2);
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch2, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch2, CURLOPT_USERAGENT, 'Mozilla/5.0');
    $response2 = curl_exec($ch2);
    $http_code2 = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
    curl_close($ch2);
    
    if ($http_code2 == 200 && $response2) {
        $data2 = json_decode($response2, true);
        if ($data2 && isset($data2['ip'])) {
            $result = [
                'status' => 'success',
                'code' => 200,
                'ip' => $data2['ip'],
                'country' => $data2['country_name'] ?? 'Unknown',
                'country_code' => $data2['country_code'] ?? null,
                'city' => $data2['city'] ?? 'Unknown',
                'region' => $data2['region'] ?? 'Unknown',
                'latitude' => $data2['latitude'] ?? null,
                'longitude' => $data2['longitude'] ?? null,
                'isp' => $data2['org'] ?? 'Unknown',
                'timezone' => $data2['timezone'] ?? null,
                'postal' => $data2['postal'] ?? null,
                'currency' => $data2['currency'] ?? null
            ];
        }
    }
}

// If both methods fail, return error
if (!$result) {
    http_response_code(503);
    $error_data = [
        'status' => 'error',
        'code' => 503,
        'message' => 'Unable to fetch IP information from external services',
        'ip' => $ip
    ];
    
    // Support JSONP callback
    if (!empty($_GET['callback'])) {
        $callback = preg_replace('/[^a-zA-Z0-9_.]/', '', $_GET['callback']);
        echo $callback . '(' . json_encode($error_data, JSON_UNESCAPED_UNICODE) . ');';
    } else {
        echo json_encode($error_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }
    exit;
}

// Support JSONP callback
if (!empty($_GET['callback'])) {
    header('Content-Type: application/javascript; charset=utf-8');
    $callback = preg_replace('/[^a-zA-Z0-9_.]/', '', $_GET['callback']);
    echo $callback . '(' . json_encode($result, JSON_UNESCAPED_UNICODE) . ');';
} else {
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
?>
