<?php
declare(strict_types=1);

/**
 * /functional/security/anti_spam.php
 * Збереження антиспам-налаштувань + ручне позначення/очищення акаунта.
 */

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

$adminCsrfFile = __DIR__ . '/../../admin/_csrf.php';
if (is_file($adminCsrfFile)) {
    require_once $adminCsrfFile;
}

$pdo = function_exists('db') ? db() : null;

$back = trim((string)($_POST['back'] ?? ''));
if ($back === '' || $back[0] !== '/') {
    $back = '/admin/antispam/';
}

$redirect = static function (string $url): void {
    if (!headers_sent()) {
        header('Location: ' . $url);
    }
    exit;
};

if (!($pdo instanceof PDO)) {
    $redirect('/admin/antispam/?err=db');
}

$sessionGet = static function (string $key): string {
    return isset($_SESSION[$key]) && is_string($_SESSION[$key]) ? (string)$_SESSION[$key] : '';
};

$postedToken = '';
if (isset($_POST['csrf_token']) && is_string($_POST['csrf_token'])) {
    $postedToken = (string)$_POST['csrf_token'];
}
if ($postedToken === '' && isset($_POST['csrf']) && is_string($_POST['csrf'])) {
    $postedToken = (string)$_POST['csrf'];
}

$csrfOk = false;
if ($postedToken !== '') {
    foreach (['admin_csrf', 'csrf', 'csrf_token'] as $sessionKey) {
        $sessionToken = $sessionGet($sessionKey);
        if ($sessionToken !== '' && hash_equals($sessionToken, $postedToken)) {
            $csrfOk = true;
            break;
        }
    }
}

if (!$csrfOk) {
    $join = str_contains($back, '?') ? '&' : '?';
    $redirect($back . $join . 'err=csrf');
}

$action = trim((string)($_POST['action'] ?? 'save_settings'));
$adminId = (int)(current_user()['id'] ?? 0);

try {
    if ($action === 'save_settings') {
        antispam_save_settings($pdo, [
            'enabled'                => (int)($_POST['enabled'] ?? 0),
            'mark_status'            => (string)($_POST['mark_status'] ?? 'bot'),
            'new_account_window_min' => (int)($_POST['new_account_window_min'] ?? 60),
            'post_limit'             => (int)($_POST['post_limit'] ?? 5),
            'comment_limit'          => (int)($_POST['comment_limit'] ?? 10),
            'link_limit'             => (int)($_POST['link_limit'] ?? 1),
            'duplicate_text_limit'   => (int)($_POST['duplicate_text_limit'] ?? 2),
            'stop_words'             => (string)($_POST['stop_words'] ?? ''),
            'stop_words_posts'       => (int)($_POST['stop_words_posts'] ?? 0),
            'stop_words_comments'    => (int)($_POST['stop_words_comments'] ?? 0),
        ]);
        $redirect('/admin/antispam/?ok=antispam');
    }

    if ($action === 'mark_user') {
        $userId = (int)($_POST['user_id'] ?? 0);
        $status = (string)($_POST['status'] ?? 'bot');
        if (!in_array($status, ['suspect', 'bot'], true)) {
            $status = 'bot';
        }

        if ($userId > 0) {
            antispam_flag_user(
                $pdo,
                $userId,
                $status,
                'manual_admin',
                $status === 'suspect' ? 'Ручна позначка адміном: підозрілий' : 'Ручна позначка адміном: бот',
                ['source' => 'admin/users'],
                $adminId,
                true
            );
        }

        $redirect($back);
    }

    if ($action === 'clear_user') {
        $userId = (int)($_POST['user_id'] ?? 0);
        if ($userId > 0) {
            antispam_clear_user($pdo, $userId);
        }
        $redirect($back);
    }
} catch (Throwable $e) {
    $join = str_contains($back, '?') ? '&' : '?';
    $redirect($back . $join . 'err=save');
}

$redirect($back);
