<?php
/**
 * Initialize the shortcode
 * <div class="hide">[honeypot usercodeid]</div>
 */
// تسجيل شورتكود الـ Honeypot
add_action( 'wpcf7_init', 'ds1_honeypot_add_form_tag', 10 );
function ds1_honeypot_add_form_tag() {
    wpcf7_add_form_tag( 
        ['honeypot'], 
        'ds1_honeypot_form_tag_handler', 
        array( 
            'name-attr' => true, 
            'do-not-store' => 0,
            'not-for-mail' => true,
        )
    );
}

// توليد الحقل المخفي
function ds1_honeypot_form_tag_handler( $tag ) {
    $tag = ( class_exists( 'wpcf7_FormTag' ) ) ? new wpcf7_FormTag( $tag ) : new wpcf7_Shortcode( $tag );
    if ( empty( $tag->name ) ) {
        return '';
    }
    $validation_error = wpcf7_get_validation_error( $tag->name );
    $class = wpcf7_form_controls_class( 'text' );
    
    $placeholder = (string) reset( $tag->values );
    $accessibility_message = __( 'Please leave this field empty.', 'contact-form-7-honeypot' );
    $atts = array(
        'class'             => $tag->get_class_option( $class ),
        'id'                => $tag->get_option( 'id', 'id', true ),
        'wrapper_id'        => $tag->get_option( 'wrapper-id' ),
        'placeholder'       => ( $placeholder ) ? $placeholder : 'UserName valid',
        'message'           => apply_filters( 'wpcf7_honeypot_accessibility_message', $accessibility_message ),
        'name'              => $tag->name,
        'type'              => $tag->type,
        'validautocomplete' => ( $tag->get_option( 'validautocomplete' ) ) ? $tag->get_option( 'validautocomplete' ) : array( 'false' ),
        'move_inline_css'    => ( $tag->get_option( 'move-inline-css' ) ) ? $tag->get_option( 'move-inline-css' ) : array( 'false' ),
        'nomessage'         => ( $tag->get_option( 'nomessage' ) ) ? $tag->get_option( 'nomessage' ) : array( 'false' ),
        'validation_error'  => $validation_error,
        // أخفي الحقل بطريقة لا تكشفه بعض البوتات الحديثة
        'css'               => apply_filters( 'wpcf7_honeypot_container_css', 'position:absolute; left:-9999px; top:auto; width:1px; height:1px; overflow:hidden;' ),
    );
    $unique_id = uniqid( 'wpcf7-' );
    $wrapper_id = ( ! empty($atts['wrapper_id'] ) ) ? reset( $atts['wrapper_id'] ) : $unique_id . '-wrapper';
    $input_placeholder = ( ! empty( $atts['placeholder'] ) ) ? ' placeholder="' . esc_attr($atts['placeholder']) . '" ' : '';
    $input_id = ( ! empty( $atts['id'] ) ) ? $atts['id'] : $unique_id . '-field';
    $autocomplete_value = ( $atts['validautocomplete'][0] === 'true' ) ? 'off' : 'new-password';
    // تحريك CSS حسب الإعداد
    if ( ! empty( $atts['move_inline_css'] ) && $atts['move_inline_css'][0] === 'true' ) {
        $hp_css = '#' . $wrapper_id . ' {' . $atts['css'] . '}';
        wp_register_style( $unique_id . '-inline', false );
        wp_enqueue_style( $unique_id . '-inline' );
        wp_add_inline_style( $unique_id . '-inline', $hp_css );
        $el_css = '';
    } else {
        $el_css = 'style="' . esc_attr($atts['css']) . '"';
    }
    $html = '<span id="' . esc_attr($wrapper_id) . '" class="wpcf7-form-control-wrap ' . esc_attr($atts['name']) . '-wrap" ' . $el_css . '>';
    if ( empty( $atts['nomessage'] ) || $atts['nomessage'][0] === 'false' ) {
        $html .= '<label for="' . esc_attr($input_id) . '" class="hp-message">' . esc_html($atts['message']) . '</label>';
    }
    $html .= '<input id="' . esc_attr($input_id) . '"' . $input_placeholder . 'class="' . esc_attr($atts['class']) . '"  type="text" name="' . esc_attr($atts['name']) . '" value="" size="40" tabindex="-1" autocomplete="'. esc_attr($autocomplete_value) . '" />';
    $html .= $validation_error . '</span>';
    return $html;
}

// فحص السبام - دمج الفلترين مع تحسين الريجكس + فحص الوقت (اختياري)
add_filter( 'wpcf7_spam', 'ds1_honeypot_spam_check', 10, 2 );
function ds1_honeypot_spam_check( $spam, $submission = null ) {
    if ( $spam ) {
        return $spam;
    }
    $co2oooform = wpcf7_ContactForm::get_current();
    $form_tags = $co2oooform->scan_form_tags();

    $hp_ids = [];
    foreach ( $form_tags as $tag ) {
        if ( $tag->type == 'honeypot' ) {
            $hp_ids[] = $tag->name;
        }
    }
    // تحقق من وجود حقول honeypot
    if ( empty( $hp_ids ) ) {
        return $spam;
    }
    // تحقق من تعبئة الحقول المخفية
    foreach ( $hp_ids as $hpid ) {
        $value = isset( $_POST[$hpid] ) ? trim($_POST[$hpid]) : '';
        if ( $value !== '' ) {
            $spam = true;
            if ( $submission ) {
                $submission->add_spam_log( array(
                    'agent' => 'honeypot',
                    'reason' => sprintf(
                        __( 'Something is stuck in the honey. Field ID = %s', 'contact-form-7-honeypot' ),
                        $hpid
                    ),
                ) );
            }
            return $spam;
        }
    }

    // تحقق من وجود روابط أو كلمات مشبوهة في الحقول (باستثناء البريد، الملف، والرابط)
    foreach ( $form_tags as $tag ) {
        if ( in_array($tag->type, ['email', 'email*', 'file', 'file*', 'url', 'url*']) || in_array('avil_links', $tag->options) ) {
            continue;
        }
        $value = isset( $_POST[$tag->name] ) ? htmlspecialchars(trim($_POST[$tag->name])) : '';
        if ( preg_match('/https?:\/\/[^\s"]+|www\.[^\s"]+|mailto:[^\s"]+/i', $value) || stripos($value, 'SEO') !== false ) {
            $spam = true;
            if ( $submission ) {
                $submission->add_spam_log( array(
                    'agent' => 'honeypot',
                    'reason' => sprintf(
                        __( 'Suspicious content detected in field ID = %s', 'contact-form-7-honeypot' ),
                        $tag->name
                    ),
                ) );
            }
            return $spam;
        }
    }

    // ** فحص توقيت الإرسال (اختياري) **
    if ( isset($_POST['form_start_time']) ) {
        $start_time = intval($_POST['form_start_time']);
        if ( $start_time > 0 && (time() - $start_time) < 5 ) { // أقل من 5 ثواني
            $spam = true;
            if ( $submission ) {
                $submission->add_spam_log( array(
                    'agent' => 'honeypot',
                    'reason' => __( 'Form submitted too quickly, possible bot.', 'contact-form-7-honeypot' ),
                ) );
            }
            return $spam;
        }
    }

    return $spam;
}
