<?php
require '../db_config.php';

function rate_limit($api_key) {
    global $pdo;

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM api_requests WHERE api_key = ? AND timestamp >= NOW() - INTERVAL 1 MINUTE");
    $stmt->execute([$api_key]);
    $request_count = $stmt->fetchColumn();

    if ($request_count >= 60) {
        http_response_code(429);
        echo json_encode(["error" => "Rate limit exceeded. Try again later."]);
        exit();
    }

    $stmt = $pdo->prepare("INSERT INTO api_requests (api_key, timestamp) VALUES (?, NOW())");
    $stmt->execute([$api_key]);
}
?>
