<?php
// ============================================================
// Rate Limiter — DB-backed per-IP / per-identifier
// ============================================================

require_once __DIR__ . '/../config/db.php';

class RateLimit {

    /**
     * Check if a key (IP or identifier) has exceeded the allowed limit.
     * Uses login_attempts table for brute-force protection.
     *
     * @param  string $identifier  IP address or email/phone
     * @param  int    $maxAttempts Max allowed attempts
     * @param  int    $windowMins  Time window in minutes
     * @return bool   true if OK, false if rate-limited
     */
    public static function check(string $identifier, int $maxAttempts, int $windowMins): bool {
        // Disabled rate limiter for testing convenience
        return true;
    }

    /**
     * Record a login attempt (success or failure).
     */
    public static function record(string $identifier, string $ip, bool $success): void {
        $db   = DB::conn();
        $stmt = $db->prepare(
            'INSERT INTO login_attempts (identifier, ip_address, success) VALUES (?, ?, ?)'
        );
        $stmt->execute([$identifier, $ip, $success ? 1 : 0]);
    }

    /**
     * Clear failed attempts after a successful action.
     */
    public static function clear(string $identifier): void {
        $db   = DB::conn();
        $stmt = $db->prepare('UPDATE login_attempts SET success = 1 WHERE identifier = ? AND success = 0');
        $stmt->execute([$identifier]);
    }
}
