<?php
// rate_limit.php

/**
 * Fungsi untuk menerapkan rate limiting.
 *
 * @param PDO $pdo Koneksi database PDO.
 * @param int $max_requests Maksimum permintaan dalam jangka waktu.
 * @param int $time_window Jangka waktu dalam detik.
 * @param string $identifier Identifier unik (misalnya IP + Endpoint).
 */
function rate_limit($pdo, $max_requests = 60, $time_window = 60, $identifier = '') {
    if (empty($identifier)) {
        $ip = $_SERVER['REMOTE_ADDR'];
        $endpoint = $_SERVER['REQUEST_URI'];
        $identifier = $ip . ':' . $endpoint;
    }

    try {
        // Hapus entri yang sudah kadaluwarsa
        $stmt = $pdo->prepare("DELETE FROM rate_limits WHERE last_request < ?");
        $time_threshold = date('Y-m-d H:i:s', time() - $time_window);
        $stmt->execute([$time_threshold]);

        // Cek jumlah permintaan
        $stmt = $pdo->prepare("SELECT request_count FROM rate_limits WHERE identifier = ?");
        $stmt->execute([$identifier]);
        $row = $stmt->fetch();

        if ($row) {
            if ($row['request_count'] >= $max_requests) {
                http_response_code(429); // Too Many Requests
                echo json_encode(['error' => 'Too many requests. Please try again later.']);
                exit;
            } else {
                // Update jumlah permintaan
                $stmt = $pdo->prepare("UPDATE rate_limits SET request_count = request_count + 1, last_request = NOW() WHERE identifier = ?");
                $stmt->execute([$identifier]);
            }
        } else {
            // Insert entri baru
            $stmt = $pdo->prepare("INSERT INTO rate_limits (identifier, request_count, last_request) VALUES (?, 1, NOW())");
            $stmt->execute([$identifier]);
        }
    } catch (Exception $e) {
        // Jika terjadi kesalahan, log dan lanjutkan (jangan menghentikan request)
        log_activity("Rate limiting error: " . $e->getMessage());
    }
}
?>
