<?php

if (!defined('ABSPATH')) {
    exit; // Pas d'accès direct !
}

function hpixl_securicheck_calculate_spam_score($commentdata)
{
    $score = 0;

    // 🔹 Honeypot rempli = bot évident (signal FORT)
    if (!empty($_POST['hpixl_securicheck_hp'])) {
        $score += 60;
    }

    // 🔹 Honeypot absent = signal FAIBLE
    if (!array_key_exists('hpixl_securicheck_hp', $_POST)) {
        $score += 10;
    }

    // 🔹 Timestamp
    if (!isset($_POST['hpixl_securicheck_timestamp'])) {
        // Champ manquant = suspect
        $score += 10;
    } else {
        $ts  = intval($_POST['hpixl_securicheck_timestamp']);
        $sig = sanitize_text_field(wp_unslash($_POST['hpixl_securicheck_timestamp_sig'] ?? ''));

        if (!hash_equals(wp_hash($ts), $sig)) {
            // Signature invalide = timestamp falsifié
            $score += 30;
        } else {
            $elapsed = time() - $ts;

            // Trop rapide = comportement bot
            if ($elapsed < 5) {
                $score += 20;
            }

            // Très rapide = encore plus suspect
            if ($elapsed < 2) {
                $score += 10;
            }
        }
    }

    // 🔹 Nonce (sécurité anti requêtes directes)
    if (!isset($_POST['hpixl_securicheck_nonce']) || !wp_verify_nonce($_POST['hpixl_securicheck_nonce'], 'hpixl_securicheck_comment_nonce')) {
        $score += 25;
    }

    // 🔹 Nombre de liens
    $links = substr_count($commentdata['comment_content'], 'http');

    if ($links > 2) {
        $score += 30;
    } elseif ($links > 0) {
        $score += 10;
    }

    // 🔹 Mots-clés spam (signal modéré)
    $keywords = ['viagra', 'casino', 'crypto', 'loan'];

    foreach ($keywords as $k) {
        if (stripos($commentdata['comment_content'], $k) !== false) {
            $score += 15;
        }
    }

    // 🔹 Email suspect (très basique mais utile)
    if (!empty($commentdata['comment_author_email'])) {
        $email = $commentdata['comment_author_email'];

        if (preg_match('/(mailinator|tempmail|10minutemail)/i', $email)) {
            $score += 20;
        }
    }

    // 🔹 IP déjà suspecte (si tu ajoutes ta logique plus tard)
    $current_ip = hpixl_securicheck_get_ip();
    if (!empty($current_ip) && function_exists('hpixl_securicheck_is_bad_ip')) {
        if (hpixl_securicheck_is_bad_ip($current_ip)) {
            $score += 40;
        }
    }

    return $score;
}

add_action('comment_form_after_fields', 'hpixl_securicheck_add_antispam_fields');
add_action('comment_form_logged_in_after', 'hpixl_securicheck_add_antispam_fields');

function hpixl_securicheck_add_antispam_fields()
{
    if (!get_option('hpixl_securicheck_toggle_page_anti_spam_commentaires')) {
        return;
    }
?>

    <!-- Honeypot -->
    <p style="display:none;">
        <input type="text" name="hpixl_securicheck_hp" value="">
    </p>

    <!-- Timestamp -->
    <?php $ts = time(); ?>
    <input type="hidden" name="hpixl_securicheck_timestamp" value="<?php echo $ts; ?>">
    <input type="hidden" name="hpixl_securicheck_timestamp_sig" value="<?php echo wp_hash($ts); ?>">

    <!-- Nonce de sécurité -->
    <?php wp_nonce_field('hpixl_securicheck_comment_nonce', 'hpixl_securicheck_nonce'); ?>

<?php
}


add_filter('preprocess_comment', 'hpixl_securicheck_handle_spam_protection');

function hpixl_securicheck_handle_spam_protection($commentdata)
{
    if (!get_option('hpixl_securicheck_toggle_page_anti_spam_commentaires')) {
        return $commentdata;
    }

    $is_audit = !empty($GLOBALS['hpixl_securicheck_running_audit_test']) ? 1 : 0;

    $score = hpixl_securicheck_calculate_spam_score($commentdata);

    // 🔴 Spam direct
    if ($score >= 60) {

        hpixl_securicheck_log_spam($commentdata, $score, 'high_score', $is_audit);

        add_filter('pre_comment_approved', function () {
            return 'spam';
        });
    }

    // 🟡 Suspect → modération
    elseif ($score >= 30) {

        hpixl_securicheck_log_spam($commentdata, $score, 'medium_score', $is_audit);

        add_filter('pre_comment_approved', function () {
            return 0;
        });
    }

    // 🟢 OK → publié normalement

    return $commentdata;
}

function hpixl_securicheck_log_spam($commentdata, $score, $reason = '', $is_audit = 0)
{
    global $wpdb;

    $table_name = $wpdb->prefix . HPIXL_SECURICHECK_TABLE_ANTISPAM_COMMENTAIRES_LOGS;

    $wpdb->insert(
        $table_name,
        [
            'ip'         => hpixl_securicheck_get_ip(),
            'email'      => $commentdata['comment_author_email'] ?? '',
            'content'    => substr($commentdata['comment_content'], 0, 1000),
            'score'      => $score,
            'reason'     => $reason,
            'is_audit'   => (int) $is_audit,
            'created_at' => current_time('mysql', true),
        ],
        ['%s', '%s', '%s', '%d', '%s', '%d', '%s']
    );
}

function hpixl_securicheck_is_spam_commentaires_protected()
{
    // Simule les données POST d'un bot : honeypot rempli, pas de nonce ni timestamp.
    // Cela déclenche notre plugin via preprocess_comment.
    $post_backup = $_POST;
    $_POST['hpixl_securicheck_hp'] = 'bot';
    unset($_POST['hpixl_securicheck_nonce'], $_POST['hpixl_securicheck_timestamp'], $_POST['hpixl_securicheck_timestamp_sig']);

    $GLOBALS['hpixl_securicheck_running_audit_test'] = true;

    // Contenu délibérément spammé : déclenche les plugins basés sur le contenu (Akismet,
    // Antispam Bee, etc.). "viagra-test-123" est le trigger de test documenté d'Akismet.
    $commentdata = [
        'comment_post_ID'      => 0,
        'comment_author'       => 'viagra-test-123',
        'comment_author_email' => 'securicheck-audit-test@example.com',
        'comment_author_url'   => 'http://spam.example.com',
        'comment_content'      => 'Buy cheap viagra online! Best casino deals! http://spam.example.com http://spam2.example.com',
        'comment_type'         => '',
    ];

    // Étape 1 — preprocess_comment : les plugins font leur analyse (appel API Akismet,
    // vérification honeypot, etc.) et stockent leur verdict dans $commentdata.
    $commentdata_processed = apply_filters('preprocess_comment', $commentdata);

    // Étape 2 — pre_comment_approved : les plugins lisent leur verdict et retournent
    // le statut final. Aucune insertion en BDD, aucun hook comment_post déclenché.
    $statut = apply_filters('pre_comment_approved', '1', $commentdata_processed);

    unset($GLOBALS['hpixl_securicheck_running_audit_test']);
    $_POST = $post_backup;

    // Les statuts natifs WordPress sans plugin anti-spam : '1' (approuvé) ou '0' (modération)
    // Tout autre statut indique qu'une protection a intercepté le commentaire.
    $statuts_normaux_wp = ['1', '0'];

    return !in_array($statut, $statuts_normaux_wp, true);
}

function hpixl_securicheck_is_bad_ip($ip)
{
    global $wpdb;

    $table = $wpdb->prefix . HPIXL_SECURICHECK_TABLE_ANTISPAM_COMMENTAIRES_LOGS;

    $count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM %i WHERE ip = %s AND score >= 60",
        $table,
        $ip
    ));

    return $count >= 5;
}
