#!/bin/bash

echo "🛡️ Déploiement du Bouclier V5 (Filtre JSON & PayPal)..."

find ./sites ./web -maxdepth 3 -name "wp-config.php" -type f 2>/dev/null | while read -r config_file; do
    site_dir=$(dirname "$config_file")
    mu_dir="$site_dir/wp-content/mu-plugins"
    plugin_file="$mu_dir/perfline-anti-carding.php"

    echo "▶ Traitement de : $site_dir"
    mkdir -p "$mu_dir"

    cat << 'EOF' > "$plugin_file"
<?php
/**
 * Plugin Name: Perfline Anti-Carding Shield
 * Description: Bloque les attaques JSON headless et l'exploit PayPal Payments.
 * Version: 5.0 (Ultimate)
 * Author: Perfline SA
 */

if ( ! defined( 'ABSPATH' ) ) exit;

function perfline_get_ip() {
    $headers = ['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
    foreach ($headers as $h) { if (!empty($_SERVER[$h])) return trim(explode(',', $_SERVER[$h])[0]); }
    return '0.0.0.0';
}

function perfline_log_block( $reason ) {
    $ip = perfline_get_ip();
    $date = date( 'Y-m-d H:i:s' );
    @error_log( "[{$date}] BLOQUÉ - IP: {$ip} - RAISON: {$reason}\n", 3, WP_CONTENT_DIR . '/perfline-shield.log' );
}

add_action( 'init', 'perfline_ultimate_bot_blocker', 1 );
function perfline_ultimate_bot_blocker() {
    if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) return;

    $uri = $_SERVER['REQUEST_URI'] ?? '';

    // 1. BLOCAGE DU STORE API WOOCOMMERCE (Bypass .htaccess)
    // Les bots utilisent l'API Store pour remplir le panier en douce. FunnelKit n'en a pas besoin.
    if ( strpos( $uri, 'wp-json/wc/store/' ) !== false ) {
        perfline_log_block( "Tentative d'utilisation du Store API ({$uri})" );
        status_header( 403 ); exit('Access Denied (API).');
    }

    // 2. BLOCAGE DE L'EXPLOIT PAYPAL (La signature du Bot)
    // On analyse les requêtes envoyées spécifiquement à PayPal
    if ( strpos( $uri, 'wc-ajax=ppc-create-order' ) !== false ) {
        $raw_data = file_get_contents('php://input');
        if ( !empty($raw_data) ) {
            $json = json_decode($raw_data, true);
            
            // Si c'est une création de commande depuis le checkout...
            if ( isset($json['context']) && $json['context'] === 'checkout' ) {
                // ...et que le formulaire encodé est vide (Signature du bot !)
                if ( empty($json['form_encoded']) ) {
                    perfline_log_block( "Exploit PayPal détecté (form_encoded vide)" );
                    status_header( 403 ); exit('Access Denied (PP).');
                }
            }
        }
    }
}

// 3. HONEYPOT CLASSIQUE (Pour les bots plus basiques)
add_filter( 'woocommerce_checkout_fields' , 'perfline_add_trap_fields' );
function perfline_add_trap_fields( $fields ) {
    $fields['billing']['billing_fax_company_ext'] = array(
        'type' => 'text', 'class' => array('perfline-hp-hidden'), 'required' => false,
    );
    return $fields;
}
add_action('wp_head', function() {
    echo '<style>.perfline-hp-hidden { display: none !important; opacity: 0 !important; position: absolute !important; left: -9999px !important; z-index: -1 !important; }</style>';
});
add_action('woocommerce_checkout_process', function() {
    if ( ! empty( $_POST['billing_fax_company_ext'] ) ) {
        perfline_log_block( 'Honeypot classique rempli' );
        status_header( 403 ); exit('Access Denied (HP).');
    }
});
EOF

    echo "   ✅ Bouclier V5 déployé avec succès."
done

echo "🎉 Terminé ! Les portes dérobées sont condamnées."