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

// Ambil parameter IP dari GET
$ip = isset($_GET['ip']) ? trim($_GET['ip']) : '';
if ($ip === '') {
    echo json_encode(['error' => 'Missing ip parameter']);
    exit;
}

// Validasi sederhana
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    echo json_encode(['error' => 'Invalid IP address']);
    exit;
}

// Endpoint API yang benar
$url = "http://ip-api.com/json/{$ip}?fields=status,message,country,regionName,city,lat,lon,query";

// Setup cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Tambahkan User-Agent agar tidak diblokir
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "User-Agent: H Shop/1.0 (admin@apg-groups.com)"
]);

$response = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

// Cek error
if ($response === false || $httpStatus !== 200) {
    echo json_encode([
        'error' => 'Failed to contact IP lookup API',
        'details' => $error,
        'status_code' => $httpStatus
    ]);
    exit;
}

// Decode untuk validasi status response
$data = json_decode($response, true);
if (!$data || !isset($data['status']) || $data['status'] !== 'success') {
    echo json_encode([
        'error' => $data['message'] ?? 'IP lookup failed',
        'raw' => $data
    ]);
    exit;
}

// Format output konsisten
echo json_encode([
    'ip' => $data['query'] ?? $ip,
    'country_name' => $data['country'] ?? '',
    'region' => $data['regionName'] ?? '',
    'city' => $data['city'] ?? '',
    'latitude' => $data['lat'] ?? null,
    'longitude' => $data['lon'] ?? null
], JSON_UNESCAPED_UNICODE);
