<?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;

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

// Independent Divi form scanning function
function formshield_scan_divi_contact_forms(): array {
    global $wpdb;
    
    // Clear cache to force rescan with new CF7 detection
    wp_cache_delete('formshield_divi_improved_posts', 'formshield');
    
    // Use WordPress Core API instead of direct database queries
    $cache_key = 'formshield_divi_improved_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
        }
    }
    
    // Parent модулът е достатъчен индикатор за Divi форми
    return (bool) preg_match('/\[et_pb_contact_form\b[^\]]*\]/i', $content);
}

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

// 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 Divi badges
			 */
			add_action( 'wp_footer', array( __CLASS__, 'add_divi_badges' ), 5 );
		}

		/*
		 * Get Divi Contact Forms using improved scanning
		 * This should return the forms list
		 *
		 * @return Array $forms_list
		 */
		public static function get_forms( $forms_list ) {
			
			// Use the new independent scanning function
			$divi_forms = formshield_scan_divi_contact_forms();
			
			
			$additional_forms = array();
			
			foreach ( $divi_forms as $divi_form ) {
				$fid = $divi_form['id'];
				
				
				$additional_forms[] = array(
					'id'          => $fid,
					'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
					'name'        => $divi_form['title'] . ' - Divi Contact Form',
					'type'        => $divi_form['type'],
					'location'    => 'Post ID: ' . $divi_form['post_id'],
					'submissions' => FormShieldForms::get_form_submissions_ct( $fid, 0 ),
					'activity'    => FormShieldForms::get_latest_form_activity( $fid, get_the_modified_date( 'Y-m-d H:i:s', $divi_form['post_id'] ) )
				);
			}
			
			return array_merge( $forms_list, $additional_forms );
		}

		/**
		 * Add JavaScript validation for Divi forms
		 */
		public static function add_divi_validation_script() {
			// Enqueue improved Divi script
			wp_enqueue_script( 'formshield-divi-improved', plugins_url( 'js/divi-forms-improved.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
			
			// Localize script with data
			wp_localize_script( 'formshield-divi-improved', 'formshieldDiviData', array(
				'protectedForms' => $protected_divi_forms,
				'badge' => FormShield_Safe::badge_html_for_js( 'Divi Contact Form' )
			) );
		}

		/**
		 * Add badges to Divi forms
		 */
		public static function add_divi_badges() {
			// Check if user should see badges
			if ( !FormShield::should_show_badge() ) {
				return;
			}

			// Get protected forms
			$options = FormShield::get_options();
			$protected_forms = array();
			
			if ( isset( $options['forms'] ) && is_array( $options['forms'] ) ) {
				foreach ( $options['forms'] as $form_id => $form_data ) {
					if ( strpos( $form_id, 'divi-' ) === 0 && isset( $form_data['enabled'] ) && $form_data['enabled'] ) {
						$protected_forms[] = $form_id;
					}
				}
			}

			if ( empty( $protected_forms ) ) {
				return;
			}

			// Enqueue badge script
			wp_enqueue_script( 'formshield-divi-improved', plugins_url( 'js/divi-forms-improved.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
			
			// Localize script with data
			wp_localize_script( 'formshield-divi-improved', 'formshieldDiviData', array(
				'protectedForms' => $protected_forms,
				'badge' => FormShield_Safe::badge_html_for_js( 'Divi Contact Form' )
			) );
		}
	}

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

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