<?php defined('BASEPATH') or exit('No direct script access allowed');

class Throttle
{
    private $CI;

    public function __construct()
    {
        $this->CI = &get_instance();
    }

    public function check($limit, $time)
    {
        $this->CI->load->library('session');

        $requests = $this->CI->session->userdata('throttle_requests');
        $lastRequestTime = $this->CI->session->userdata('throttle_last_request_time');

        if (!$requests || !$lastRequestTime) {
            $requests = 1;
            $lastRequestTime = time();
        } else {
            $elapsedTime = time() - $lastRequestTime;
            if ($elapsedTime <= $time) {
                $requests++;
            } else {
                $requests = 1;
                $lastRequestTime = time();
            }
        }

        $this->CI->session->set_userdata('throttle_requests', $requests);
        $this->CI->session->set_userdata('throttle_last_request_time', $lastRequestTime);

        return $requests <= $limit;
    }
}
