<?php
// --- rate_limit.php (include at top of list_lookup.php) ---
$store = __DIR__ . '/rate_limits.json';
//$ip    = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
# If multiple IPs (comma separated), take the first (original client)
if (strpos($ip, ',') !== false) {
    $ip = trim(explode(',', $ip)[0]);
}

$today = (new DateTime('now', new DateTimeZone('UTC')))->format('Y-m-d');
$limit = 2;

$all = [];
if (file_exists($store)) {
  $json = file_get_contents($store);
  $all = json_decode($json, true) ?: [];
}

// reset other days automatically
$count = $all[$ip][$today] ?? 0;
if ($count >= $limit) {
  http_response_code(429);
  header('Content-Type: application/json');
  echo json_encode([
    'ok' => false,
    'error' => 'rate_limit_exceeded',
    'message' => 'You have reached today’s free lookup limit.',
    'limit' => $limit
  ]);
  exit;
}

// increment (do this just before returning OK later if you prefer “on success”)
$all[$ip] = [$today => $count + 1];
@file_put_contents($store, json_encode($all, JSON_PRETTY_PRINT));