<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Rate-limit login attempts (5 failures / 15 min per email+IP).
 */
class LoginThrottleFilter implements FilterInterface
{
    private const MAX_ATTEMPTS = 5;
    private const WINDOW_MIN   = 15;

    public function before(RequestInterface $request, $arguments = null)
    {
        if (strtolower($request->getMethod()) !== 'post') {
            return;
        }

        $uri = $request->getUri()->getPath();
        if (!str_contains($uri, 'login')) {
            return;
        }

        $db = \Config\Database::connect();
        if (!$db->tableExists('login_attempts')) {
            return;
        }

        $email = strtolower(trim($request->getPost('email') ?? ''));
        $ip    = $request->getIPAddress();
        if ($email === '') {
            return;
        }

        $since = date('Y-m-d H:i:s', strtotime('-' . self::WINDOW_MIN . ' minutes'));
        $fails = $db->table('login_attempts')
            ->where('email', $email)
            ->where('success', 0)
            ->where('created_at >=', $since)
            ->countAllResults();

        if ($fails >= self::MAX_ATTEMPTS) {
            return redirect()->to(base_url('login'))
                ->with('error', 'Too many failed login attempts. Try again in ' . self::WINDOW_MIN . ' minutes.');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}
