<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( 'You are not allowed to call this page directly.' );
}

// Improved Divi detection function
function formshield_is_divi_active(): bool {
    // Надеждни сигнали за Divi Theme или Divi Builder
    if (defined('ET_CORE_VERSION') || defined('ET_BUILDER_PRODUCT_VERSION')) return true;
    if (class_exists('ET_Builder_Element') || class_exists('ET_Builder_Module')) return true;
    if (function_exists('et_setup_theme') || function_exists('et_core_is_builder_used_on_current_request')) return true;
    if (class_exists('ET_Builder_Module_Contact_Form')) return true;
    if (function_exists('et_pb_contact_form')) return true;

    // Проверка за Divi Plugin
    if (is_plugin_active('divi-builder/divi-builder.php')) return true;
    if (is_plugin_active('divi-builder/divi-builder.php')) return true;

    // Fallback: активна ли е тема/плъгин на Elegant Themes
    $theme = wp_get_theme();
    if (stripos($theme->get('Name'), 'Divi') !== false || stripos($theme->get('Author'), 'Elegant Themes') !== false) {
        return true;
    }
    
    // Проверка за Divi в активните теми
    $active_theme = wp_get_theme();
    $parent_theme = $active_theme->parent();
    if ($parent_theme && (stripos($parent_theme->get('Name'), 'Divi') !== false)) {
        return true;
    }
    
    return false;
}

// Check if Divi is active using improved detection
$divi_active = formshield_is_divi_active();

// Independent Divi form scanning function
function formshield_scan_divi_contact_forms(): array {
    global $wpdb;
    
    // Use WordPress Core API instead of direct database queries
    $cache_key = 'formshield_divi_posts';
    $posts = wp_cache_get($cache_key, 'formshield');
    if (false === $posts) {
        $posts = get_posts(array(
            'post_type' => array('page', 'post', 'et_pb_layout'),
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'fields' => 'ids'
        ));
        
        // Get full post data for each post
        $full_posts = array();
        foreach ($posts as $post_id) {
            $post = get_post($post_id);
            if ($post) {
                $full_posts[] = (object) array(
                    'ID' => $post->ID,
                    'post_title' => $post->post_title,
                    'post_content' => $post->post_content
                );
            }
        }
        $posts = $full_posts;
        wp_cache_set($cache_key, $posts, 'formshield', 300); // Cache for 5 minutes
    }

    $found = [];
    foreach ($posts as $p) {
        if (formshield_contains_divi_contact_form($p->post_content)) {
            $found[] = [
                'id'       => 'divi-' . $p->ID, // уникален key за таблицата
                'title'    => $p->post_title ?: ('Post #' . $p->ID),
                'type'     => 'Divi Contact Form',
                'post_id'  => $p->ID,
            ];
        }
    }
    return $found;
}

function formshield_contains_divi_contact_form(string $content): bool {
    // First check if this is a Contact Form 7 form - if so, it's not a Divi form
    $cf7_patterns = array(
        '/\[contact-form-7[^\]]*\]/i',
        '/\[contact_form_7[^\]]*\]/i',
        '/\[cf7[^\]]*\]/i',
        '/contact-form-7/i',
        '/wpcf7/i'
    );
    
    foreach ($cf7_patterns as $pattern) {
        if (preg_match($pattern, $content)) {
            return false; // This is a CF7 form, not a Divi form
        }
    }
    
    // Divi 4 patterns (shortcode format)
    $divi4_patterns = array(
        '/\[et_pb_contact_form\b[^\]]*\]/i',
        '/\[et_pb_contact_form[0-9]*\b[^\]]*\]/i',
        '/\[et_pb_module.*contact.*form/i'
    );
    
    // Divi 5 patterns (HTML/JSON format)
    $divi5_patterns = array(
        '/et_pb_contact_form[0-9]*/i',
        '/et_pb_module_contact/i',
        '/et_pb_contact/i',
        '/contact_form/i',
        '/divi.*contact.*form/i',
        '/contact.*form.*divi/i',
        '/et_pb.*contact/i',
        '/contact.*et_pb/i',
        '/data-et_pb_module_class.*contact/i',
        '/class.*et_pb_contact/i'
    );
    
    // Проверка за Divi 4 (shortcode format)
    foreach ($divi4_patterns as $pattern) {
        if (preg_match($pattern, $content)) {
            return true;
        }
    }
    
    // Проверка за Divi 5 (HTML/JSON format)
    foreach ($divi5_patterns as $pattern) {
        if (preg_match($pattern, $content)) {
            return true;
        }
    }
    
    // Допълнителна проверка за Divi Theme Builder
    if (strpos($content, 'et_pb_contact_form') !== false) {
        return true;
    }
    
    // Проверка за Divi Visual Builder content
    if (strpos($content, 'et_pb_module') !== false && strpos($content, 'contact') !== false) {
        return true;
    }
    
    return false;
}

// Check if class already exists to prevent multiple loading
$class_exists = class_exists( 'FormShieldDiviFormsIntegration' );

if ( $divi_active && !$class_exists ) {

	class FormShieldDiviFormsIntegration extends FormShieldIntegration {
		public static $form_prefix = 'divi';
		
		/*
		 * This is where you will add filters and actions
		 */
		public function __construct() {
			add_filter( 'formshield_forms_list', array( __CLASS__, 'get_forms' ), 35, 1 );
			add_action( 'wp_footer', array( __CLASS__, 'add_divi_validation_script' ) );
			add_action( 'formshield_autoprotect_forms', array( __CLASS__, 'enable_forms' ), 35, 1 );
			
			/**
			 * Add protected badge to Divi forms
			 */
			add_action( 'wp_footer', array( __CLASS__, 'add_divi_badges' ), 5 );
			
			/**
			 * Load Divi spam detection class
			 */
			require_once plugin_dir_path( dirname( __FILE__ ) ) . 'classes/class-formshield-divi-spam-detection.php';
		}

		/*
		 * Get Divi Contact Forms (Divi 4 + Divi 5)
		 * This should return the forms list
		 *
		 * @return Array $forms_list
		 */
		public static function get_forms( $forms_list ) {
			$additional_forms = array();
			
			// Clear cache to force rescan with new CF7 detection
			wp_cache_delete('formshield_divi_posts', 'formshield');
			
			// Check if Divi is active
		$divi_active = formshield_is_divi_active();
			
			// Skip old methods - use only Enhanced detection
			
			// Enhanced Divi Detection - Single optimized method for all Divi versions
			// This method replaces all previous methods (1-6) for better performance and reliability
			// It detects Divi 4, Divi 5, and future versions with a single scan
			
			$all_posts = get_posts( array(
				'post_type' => array('page', 'post', 'et_pb_layout', 'et_template'),
				'posts_per_page' => -1,
				'post_status' => 'publish'
			) );
			
			foreach ( $all_posts as $post ) {
				$content = $post->post_content;
				
				// Skip if this page contains Contact Form 7 shortcodes
				// This prevents CF7 forms from being detected as Divi forms
				$cf7_patterns = array(
					'/\[contact-form-7[^\]]*\]/i',
					'/\[contact_form_7[^\]]*\]/i',
					'/\[cf7[^\]]*\]/i',
					'/contact-form-7/i',
					'/wpcf7/i'
				);
				
				$has_cf7 = false;
				foreach ($cf7_patterns as $pattern) {
					if (preg_match($pattern, $content)) {
						$has_cf7 = true;
						break;
					}
				}
				
				if ($has_cf7) {
					continue; // Skip this post, it's a CF7 form, not a Divi form
				}
				
				// Enhanced Divi 5 patterns - only for actual Divi contact forms
				$enhanced_patterns = array(
					'/et_pb_contact_form[0-9]*/i',
					'/et_pb_module.*contact/i',
					'/divi.*contact.*form/i',
					'/contact.*form.*divi/i',
					'/et_pb.*contact/i',
					'/contact.*et_pb/i'
				);
				
				$has_contact_form = false;
				foreach ( $enhanced_patterns as $pattern ) {
					if ( preg_match( $pattern, $content ) ) {
						$has_contact_form = true;
						break;
					}
				}
				
				if ( $has_contact_form ) {
					// Extract form IDs from content (Divi can have multiple forms per page)
					$form_ids = self::extract_divi_form_ids( $content, $post->ID );
					
					foreach ( $form_ids as $form_id_data ) {
						// Use post_id + form_id for unique identification
						$fid = self::get_unique_form_id( $post->ID, $form_id_data['form_id'] );
						
						// Check if this form is already added
						$already_added = false;
						foreach ( $additional_forms as $existing_form ) {
							if ( isset( $existing_form['id'] ) && $existing_form['id'] === $fid ) {
								$already_added = true;
								break;
							}
						}
						
						// Also check if this form already exists in forms_list
						if ( !$already_added ) {
							foreach ( $forms_list as $existing_form ) {
								if ( isset( $existing_form['id'] ) && $existing_form['id'] === $fid ) {
									$already_added = true;
									break;
								}
							}
						}
						
						if ( !$already_added ) {
							$form_name = $post->post_title;
							if ( count( $form_ids ) > 1 ) {
								$form_name .= ' - Form ' . ( $form_id_data['index'] + 1 );
							}
							
							$additional_forms[] = array(
								'id'          => $fid,
								'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
								'name'        => $form_name,
								'type'        => 'Divi Contact Form',
								'location'    => get_permalink( $post->ID ),
								'plugin'      => 'Divi',
								'post_id'     => $post->ID,
								'form_id'     => $form_id_data['form_id'],
								'submissions' => FormShieldForms::get_form_submissions_ct( $fid, 0 ),
								'activity'    => FormShieldForms::get_latest_form_activity( $fid, $post->post_modified )
							);
						}
					}
				}
			}
			
			// Remove duplicate forms based on location/content similarity
			$additional_forms = self::remove_duplicate_forms( $additional_forms );
			
			// Additional cleanup: Remove forms with generic names that might be duplicates
			$additional_forms = self::cleanup_generic_forms( $additional_forms );

			self::prune_disabled_forms( $additional_forms );
			$forms_list = array_merge( $forms_list, $additional_forms );
			
			return $forms_list;
		}

		/**
		 * Add JavaScript validation for Divi forms (Divi 4 + Divi 5)
		 */
		public static function add_divi_validation_script() {
			$options = FormShield::get_options();
			
			if ( ! isset( $options['formshield_forms'] ) ) {
				return;
			}
			
			// Enqueue behavioral tracking script
			wp_enqueue_script(
				'formshield-divi-behavioral-tracking',
				plugins_url( 'js/divi-forms-behavioral-tracking.js', dirname( __FILE__ ) ),
				array( 'jquery' ),
				FORMSHIELD_VERSION,
				true
			);
			
			// Localize script with AJAX data
			wp_localize_script(
				'formshield-divi-behavioral-tracking',
				'formshieldData',
				array(
					'ajaxurl' => admin_url( 'admin-ajax.php' ),
					'nonce' => wp_create_nonce( 'formshield_protection' ),
					'postId' => get_the_ID() ? get_the_ID() : 0
				)
			);
		}
		
		/**
		 * Extract Divi form IDs from content
		 * Returns array of form identifiers
		 */
		private static function extract_divi_form_ids( $content, $post_id ) {
			$form_ids = array();
			
			// Pattern for Divi 4: [et_pb_contact_form id="123"]
			if ( preg_match_all( '/\[et_pb_contact_form[^\]]*id=["\']?(\d+)["\']?[^\]]*\]/i', $content, $matches ) ) {
				foreach ( $matches[1] as $index => $form_id ) {
					$form_ids[] = array(
						'form_id' => $form_id,
						'index' => $index
					);
				}
			}
			
			// Pattern for Divi 5: et_pb_contact_form_123 or data-form-id="123"
			if ( preg_match_all( '/et_pb_contact_form[_-]?(\d+)/i', $content, $matches ) ) {
				foreach ( $matches[1] as $index => $form_id ) {
					// Avoid duplicates
					$exists = false;
					foreach ( $form_ids as $existing ) {
						if ( $existing['form_id'] === $form_id ) {
							$exists = true;
							break;
						}
					}
					if ( !$exists ) {
						$form_ids[] = array(
							'form_id' => $form_id,
							'index' => count( $form_ids )
						);
					}
				}
			}
			
			// If no specific form IDs found, use post_id as form identifier
			if ( empty( $form_ids ) ) {
				$form_ids[] = array(
					'form_id' => 'default',
					'index' => 0
				);
			}
			
			return $form_ids;
		}
		
		/**
		 * Get unique form identifier using post_id + form_id
		 */
		private static function get_unique_form_id( $post_id, $form_id ) {
			if ( $form_id && $form_id !== 'default' ) {
				return 'divi_' . $post_id . '_' . md5( $form_id );
			}
			return 'divi_' . $post_id;
		}

		/*
		 * Protect Existing Divi forms
		 */
		public static function enable_forms( $unattended ) {
			// Get all pages with Divi contact forms
			$divi_pages = get_posts( array(
				'post_type' => 'page',
				'posts_per_page' => -1,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
				'meta_key' => '_et_pb_use_builder',
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
				'meta_value' => 'on'
			) );

			foreach ( $divi_pages as $page ) {
				if ( strpos( $page->post_content, 'et_pb_contact_form' ) !== false ) {
					$fid = self::get_form_id( $page->ID );
					FormShieldForms::enable_forms( $fid, 1, $unattended );
				}
			}
		}
		
		/**
		 * Remove duplicate forms based on location and content similarity
		 */
		private static function remove_duplicate_forms( $forms ) {
			$unique_forms = array();
			$seen_forms = array();
			
			foreach ( $forms as $form ) {
				// Create a unique key based on post ID (most reliable)
				$unique_key = '';
				
				// First try to use post_id if available
				if ( isset( $form['post_id'] ) && !empty( $form['post_id'] ) ) {
					$unique_key = 'post_' . $form['post_id'];
				} elseif ( isset( $form['id'] ) ) {
					// Extract post ID from divi5_enhanced_POSTID format
					if ( preg_match( '/divi5_enhanced_(\d+)/', $form['id'], $matches ) ) {
						$unique_key = 'post_' . $matches[1];
					} elseif ( preg_match( '/divi[_-]?(\d+)/', $form['id'], $matches ) ) {
						// Also check for divi-123 or divi_123 format
						$unique_key = 'post_' . $matches[1];
					} else {
						// Fallback to form ID
						$unique_key = $form['id'];
					}
				} else {
					// Last resort: use form name
					$unique_key = isset( $form['name'] ) ? strtolower( trim( $form['name'] ) ) : uniqid();
				}
				
				// Check if we've already seen this form
				if ( ! isset( $seen_forms[ $unique_key ] ) ) {
					$unique_forms[] = $form;
					$seen_forms[ $unique_key ] = $form;
				}
			}
			
			return $unique_forms;
		}
		
		/**
		 * Clean up generic forms that might be duplicates
		 */
		private static function cleanup_generic_forms( $forms ) {
			$cleaned_forms = array();
			$generic_patterns = array(
				'/FormShield.*интелигентна защита.*WordPress/',
				'/FormShield.*intelligent protection.*WordPress/',
				'/FormShield.*protection.*WordPress/'
			);
			
			foreach ( $forms as $form ) {
				$is_generic = false;
				
				// Check if this is a generic FormShield form
				foreach ( $generic_patterns as $pattern ) {
					if ( preg_match( $pattern, $form['name'] ) ) {
						$is_generic = true;
						break;
					}
				}
				
				if ( ! $is_generic ) {
					$cleaned_forms[] = $form;
				}
			}
			
			return $cleaned_forms;
		}
		
			/**
	 * Add protected badges to Divi forms
	 */
	public static function add_divi_badges() {
		$options = FormShield::get_options();
		
		// Check if user is logged in and has admin capabilities (admin, editor, author, contributor)
		if ( ! is_user_logged_in() || ! current_user_can( 'edit_posts' ) ) {
			return;
		}
		
		if ( ! isset( $options['formshield_forms'] ) ) {
			return;
		}
		
		// Get protected Divi forms (all types)
		$protected_divi_forms = array();
		$has_protected_divi = false;
		foreach ( $options['formshield_forms'] as $fid => $form_data ) {
			// Check for all Divi form types - добавяме проверка за 'divi_' формат
			if ( (strpos( $fid, 'divi5_enhanced_' ) === 0 || strpos( $fid, 'divi-' ) === 0 || strpos( $fid, 'divi5_' ) === 0 || strpos( $fid, 'divi_' ) === 0) && isset( $form_data['form_enabled'] ) && $form_data['form_enabled'] ) {
				$protected_divi_forms[] = $fid;
				$has_protected_divi = true;
			}
		}
		
		
		if ( !$has_protected_divi ) {
			return;
		}
		
		// Get badge HTML
		$badge_html = FormShield::badge_html( 'Divi Contact Form' );
		
		// Enqueue badge script
		wp_enqueue_script( 'formshield-divi-badge', plugins_url( 'js/divi-forms-badge.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
		
		// Localize script with badge data
		wp_localize_script( 'formshield-divi-badge', 'formshieldDiviData', array(
			'badge' => $badge_html,
			'protectedForms' => $protected_divi_forms,
			'currentPostId' => get_the_ID() ? get_the_ID() : 0
		) );
		
		// Enqueue admin styles
		wp_enqueue_style( 'formshield-admin-override', plugins_url( 'css/admin.css', dirname(__FILE__) ), array('formshield-admin'), FORMSHIELD_VERSION );
	}
	}

	add_action( 'plugins_loaded', function() { 
		try {
			$instance = new FormShieldDiviFormsIntegration(); 
		} catch ( Exception $e ) {
		}
	});

} else {
	if ( !$divi_active ) {
	} else {
	}
}
