<?php
require_once __DIR__ . '/bootstrap.php';

/**
 * Simple rate limiter
 */
function rate_limit(string $action, int $limit, int $seconds): void
{
    global $pdo;

    $id = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $now = new DateTime();

    $stmt = $pdo->prepare(
        'SELECT id, hits, reset_at
         FROM rate_limits
         WHERE identifier = :id AND action = :action'
    );
    $stmt->execute(['id' => $id, 'action' => $action]);
    $row = $stmt->fetch();

    if (!$row) {
        $pdo->prepare(
            'INSERT INTO rate_limits (identifier, action, hits, reset_at)
             VALUES (:id, :action, 1, :reset)'
        )->execute([
            'id' => $id,
            'action' => $action,
            'reset' => $now->modify("+$seconds seconds")->format('Y-m-d H:i:s')
        ]);
        return;
    }

    if ($now > new DateTime($row['reset_at'])) {
        $pdo->prepare(
            'UPDATE rate_limits
             SET hits = 1, reset_at = :reset
             WHERE id = :id'
        )->execute([
            'reset' => $now->modify("+$seconds seconds")->format('Y-m-d H:i:s'),
            'id' => $row['id']
        ]);
        return;
    }

    if ($row['hits'] >= $limit) {
        http_response_code(429);
        echo 'Too many requests';
        exit;
    }

    $pdo->prepare(
        'UPDATE rate_limits SET hits = hits + 1 WHERE id = :id'
    )->execute(['id' => $row['id']]);
}
