<?php
/**
 * ip-info.php — IP geolocation lookup endpoint
 *
 * Called by the app as one of three candidate sources (in order):
 *   {panel_url}api/ip-info.php, https://ipwho.is/, https://ipapi.co/json/
 * The app looks for an "ip" or "query" field and a "location" field
 * in the JSON response (see VpnController$7).
 *
 * This panel-hosted mirror resolves the caller's IP (honoring reverse
 * proxy headers) and proxies a lookup to a public geolocation service,
 * so the app has a first-party fallback that doesn't depend on a
 * third-party endpoint being reachable from the device.
 */

require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json; charset=UTF-8');

logRequest('api/ip-info.php');

// Resolve the client's real IP, honoring reverse proxy headers.
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
} elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
    $ip = trim($_SERVER['HTTP_X_REAL_IP']);
} else {
    $ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
}

$response = [
    'ip' => $ip,
    'query' => $ip,
    'location' => '',
];

// Best-effort upstream geolocation lookup. Fails closed: on any error,
// we still return the IP with an empty location rather than erroring out.
if ($ip !== '') {
    $context = stream_context_create([
        'http' => [
            'timeout' => 4,
            'header' => "User-Agent: IPTV-Panel/1.0\r\n",
        ],
    ]);

    $upstream = @file_get_contents(
        'https://ipwho.is/' . rawurlencode($ip),
        false,
        $context
    );

    if ($upstream !== false) {
        $data = json_decode($upstream, true);
        if (is_array($data) && !empty($data['success'])) {
            $city = $data['city'] ?? '';
            $region = $data['region'] ?? '';
            $country = $data['country'] ?? '';
            $parts = array_filter([$city, $region, $country]);
            $response['location'] = implode(', ', $parts);
        }
    }
}

echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
