<?php
declare(strict_types=1);

function rate_limit_ok(string $key, int $maxAttempts, int $windowSeconds): bool {
  $now = time();
  if (!isset($_SESSION['_op_rl'])) $_SESSION['_op_rl'] = [];
  if (!isset($_SESSION['_op_rl'][$key])) {
    $_SESSION['_op_rl'][$key] = ['count' => 0, 'start' => $now];
  }
  $bucket = &$_SESSION['_op_rl'][$key];
  if (($now - (int)$bucket['start']) > $windowSeconds) {
    $bucket = ['count' => 0, 'start' => $now];
  }
  if ((int)$bucket['count'] >= $maxAttempts) {
    return false;
  }
  $bucket['count'] = (int)$bucket['count'] + 1;
  return true;
}
