<?php
// 防止缓存
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

function is_terminal() {
  if (php_sapi_name() === 'cli') return true;
  if (!isset($_SERVER['HTTP_USER_AGENT'])) return true;
  $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
  return strpos($ua, 'curl') !== false || strpos($ua, 'wget') !== false || strpos($ua, 'httpie') !== false;
}

require_once __DIR__ . '/ipip-api-20261120.php';
$ip  = \IPIP\address($_SERVER['REMOTE_ADDR'] ?? null) ?? 'Unknown';
$ua  = $_SERVER['HTTP_USER_AGENT'] ?? 'N/A';
$now = date('Y-m-d H:i:s P e') . ' (server)';

if (is_terminal()) {
  header('Content-Type: text/plain; charset=utf-8');

  function color($text, $code = '92') { // 高亮绿色
    return "\033[" . $code . "m" . $text . "\033[0m";
  }

  function get_location($ip) {
    $flag = '';
    $location = '未知';
    $url = "https://ipwho.is/" . urlencode($ip);

    $context = stream_context_create([
      'http' => ['timeout' => 2]  // 改为 2 秒
    ]);

    $start = microtime(true);
    $json = @file_get_contents($url, false, $context);
    if ((microtime(true) - $start) > 2 || !$json) return [$location, 'Unavailable'];

    $data = json_decode($json, true);
    if (!$data || empty($data['success']) || \IPIP\address($data['ip'] ?? null) !== $ip) return [$location, 'Unavailable'];
    if (!empty($data['country_code'])) {
      foreach (str_split(strtoupper($data['country_code'])) as $char) {
        $flag .= mb_chr(127397 + ord($char));
      }
    }
    $location = trim($flag . ' ' . ($data['country'] ?? '') . (isset($data['region']) ? ', ' . $data['region'] : ''));
    $location = preg_replace('/[\x00-\x1F\x7F]/u', '', $location);
    $zone = 'Unavailable';
    $id = $data['timezone']['id'] ?? '';
    if (is_string($id) && in_array($id, timezone_identifiers_list(), true)) {
      $local = new DateTimeImmutable('now', new DateTimeZone($id));
      $zone = $id . ' (UTC' . $local->format('P') . ')';
    }
    return [$location, $zone];
  }

  $ip_color = color($ip, '92'); // 高亮绿色
  [$location, $ipZone] = \IPIP\address($ip) && \IPIP\is_public($ip) ? get_location($ip) : ['Private / reserved', 'Unavailable'];

  $label_width = 10;
  $val_width = max(strlen($ip), mb_strwidth($location, 'UTF-8'), strlen($now), strlen($ipZone));

  echo '┌' . str_repeat('─', $label_width + 2) . '┬' . str_repeat('─', $val_width + 2) . "\n";
  echo '│ ' . str_pad('IP', $label_width) . ' │ ' . $ip_color . "\n";
  echo '│ ' . str_pad('Location', $label_width) . ' │ ' . $location . "\n";
  echo '│ ' . str_pad('Time', $label_width) . ' │ ' . $now . "\n";
  echo '│ ' . str_pad('IP zone', $label_width) . ' │ ' . $ipZone . "\n";
  echo '└' . str_repeat('─', $label_width + 2) . '┴' . str_repeat('─', $val_width + 2) . "\n";
  exit;
}
?>
<?php require __DIR__ . '/ipip-web-20261119.php'; ?>
