<?php
declare(strict_types=1);

/**
 * /functional/security/rate_limit.php
 * Admin action: збереження налаштувань rate-limit (login/register)
 */

require_once __DIR__ . '/../../includes/start.php';
require_role(['admin']);

require_once __DIR__ . '/../../includes/security_rate_limit.php';

$pdo = function_exists('db') ? db() : null;
if (!($pdo instanceof PDO)) {
  if (!headers_sent()) { header('Location: /admin/security/?err=db#rate-limit'); }
  exit;
}

// CSRF
if (function_exists('csrf_verify')) {
  csrf_verify();
} else {
  $csrf = (string)($_POST['csrf'] ?? $_POST['csrf_token'] ?? '');
  $sess = (string)($_SESSION['csrf'] ?? $_SESSION['csrf_token'] ?? '');
  if ($csrf === '' || $sess === '' || !hash_equals($sess, $csrf)) {
    if (!headers_sent()) { header('Location: /admin/security/?err=csrf#rate-limit'); }
    exit;
  }
}

$attempts = (int)($_POST['attempts'] ?? 0);
$window   = (int)($_POST['window_min'] ?? 0);
$lock     = (int)($_POST['lock_min'] ?? 0);
$mode     = trim((string)($_POST['mode'] ?? 'both'));

try {
  security_rate_save_settings($pdo, $attempts, $window, $lock, $mode);
  if (!headers_sent()) { header('Location: /admin/security/?ok=rate#rate-limit'); }
  exit;
} catch (Throwable $e) {
  if (!headers_sent()) { header('Location: /admin/security/?err=save#rate-limit'); }
  exit;
}
