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

class FormShieldCF7Integration extends FormShieldIntegration {
	public static $form_prefix = 'cf7';

	/*
	 * This is where you will add filters and actions
	 */
	public function __construct() {
		add_filter( 'formshield_forms_list', array( __CLASS__, 'get_forms' ), 20, 1 );
		add_filter( 'wpcf7_spam', array( __CLASS__, 'validate_forms' ), 10, 1 );
		add_action( 'formshield_autoprotect_forms', array( __CLASS__, 'enable_forms' ), 20, 1 );

		/**
		 * Auto-protect New Contact Form 7 Forms
		 */
		add_action( 'wpcf7_after_create', array( 'FormShieldAutoProtect', 'init' ), 10, 2 );
		add_action( 'wpcf7_after_update', array( 'FormShieldAutoProtect', 'init' ), 10, 2 );
		
		/**
		 * Add protected badge to Contact Form 7 forms
		 */
		add_action( 'wp_footer', array( __CLASS__, 'add_cf7_badge_script' ), 99 );

		// Inject badge at render-time (reliable, no JS dependency)
		add_filter( 'wpcf7_form_elements', array( __CLASS__, 'inject_badge_into_form' ), 99, 1 );
	}

	/*
	 * Get Contact Form 7 forms
	 *
	 * @return Array $forms_list
	 */
	public static function get_forms( $forms_list ) {
		if ( function_exists( 'wpcf7_contact_form' ) ) {
			$additional_forms = array();
			
			$cf7_form_list = get_posts( array(
				'post_type'   => 'wpcf7_contact_form',
				'numberposts' => - 1
			) );
			
			foreach ( $cf7_form_list as $form ) {
				// Use post_name (slug) for form ID, fallback to post ID
				$cf7_slug = !empty($form->post_name) ? $form->post_name : $form->ID;
				$form_id = self::get_form_id( $cf7_slug );
				
				// Push to forms list
				$additional_forms[] = array(
					'id'          => $form_id,
					'enabled'     => FormShieldSettings::is_form_enabled( $form_id ),
					'name'        => $form->post_title,
					'type'        => 'Contact Form 7',
					'location'    => 'Contact Form 7: ' . $form->post_title . ' (ID: ' . $form->ID . ')',
					'submissions' => FormShieldForms::get_form_submissions_ct( $form_id, 0 ),
					'activity'    => FormShieldForms::get_latest_form_activity( $form_id, $form->post_modified )
				);
			}
			self::prune_disabled_forms( $additional_forms );
			$forms_list = array_merge( $forms_list, $additional_forms );
		}

		return $forms_list;
	}

	/**
	 * Validate Contact Form 7 forms
	 *
	 * @param Boolean $spam - Boolean value to return true for spammy submissions
	 *
	 * @return Boolean
	 */
	public static function validate_forms( $spam ) {
		// Skip if already marked as spam
		if ( $spam ) {
			return $spam;
		}
		
		// If HP protection enabled, validate the form
		$options = FormShield::get_options();
		$cf7_id = formshield_get_post_string('_wpcf7');
		
		// Skip if no CF7 ID found
		if ( empty( $cf7_id ) ) {
			return $spam;
		}
		
		// Get the form object to get the correct slug
		$form = get_post($cf7_id);
		$cf7_slug = $form && !empty($form->post_name) ? $form->post_name : $cf7_id;
		$form_id = self::get_form_id( $cf7_slug );
		
		// Check if this form is protected
		if ( is_array( $options ) && array_key_exists( 'formshield_forms', $options ) && isset( $options['formshield_forms'][ $form_id ] ) ) {
			$formshield_form_enabled = isset( $options['formshield_forms'][ $form_id ] ) ? $options['formshield_forms'][ $form_id ]['form_enabled'] : 0;
			
			if ( $formshield_form_enabled ) {
				// Check honeypot field first (quick check)
				$honeypot_value = formshield_get_post_string('formshield_honeypot', '');
				if ( !empty($honeypot_value) ) {
					// Honeypot was filled - definitely a bot
					FormShieldForms::handle_suspicious_form_activity( $form_id );
					$spam = true;
				} else {
					// Run FormShield validation
					$validation_failed = FormShieldForms::fail_form_validation();
					
					if ( $validation_failed ) {
						// Record suspicious activity
						FormShieldForms::handle_suspicious_form_activity( $form_id );
						
						// Mark as spam - CF7 will handle the error message
						$spam = true;
					}
				}
			}
		}

		return $spam;
	}

	/*
	 * This is for the autoprotect process and should enable all forms for validation.
	 * This should be added to the formshield_autoprotect_forms action.
	 * This should implement the FormShieldForms::enable_forms() static method to enable each form
	 */
	public static function enable_forms( $unattended ) {
		if ( function_exists( 'wpcf7_contact_form' ) ) {
			$cf7_form_list = get_posts( array(
				'post_type'   => 'wpcf7_contact_form',
				'numberposts' => - 1
			) );
			if ( is_array( $cf7_form_list ) ) {
				foreach ( $cf7_form_list as $form ) {
					// Use post_name (slug) for form ID, fallback to post ID
					$cf7_slug = !empty($form->post_name) ? $form->post_name : $form->ID;
					$form_id = self::get_form_id( $cf7_slug );
					FormShieldForms::enable_forms( $form_id, 1, $unattended );
				}
			}
		}
	}
	
	
	/**
	 * Generate JavaScript code for badge injection
	 *
	 * @param array $js_data Data to pass to JavaScript
	 * @return string JavaScript code
	 */
	private static function generate_badge_script($js_data) {
		// Check if script file exists
		$script_path = plugin_dir_path(__FILE__) . '../js/contact-form-7-inline.js';
		
		// Enqueue Contact Form 7 script first
		wp_enqueue_script('wpcf7-forms');
		
		// Enqueue our script with dependency on CF7
		wp_enqueue_script( 
			'formshield-cf7-badge', 
			plugins_url( 'js/contact-form-7-inline.js', dirname(__FILE__) ), 
			array('jquery', 'wpcf7-forms'), 
			FORMSHIELD_VERSION . '.' . time(), 
			true 
		);
		
		// Localize script with data
		wp_localize_script( 'formshield-cf7-badge', 'formshieldCF7Data', $js_data );
		
		// Return empty string since we're using enqueue
		return '';
	}

	/**
	 * Inject FormShield badge into CF7 form HTML at render time.
	 * This runs during the CF7 shortcode rendering and does not rely on JS.
	 *
	 * @param string $content Form markup
	 * @return string Modified form markup
	 */
	public static function inject_badge_into_form( $content ) {
		// Show only for admins per FormShield policy
		if ( ! FormShield::should_show_badge() ) {
			return $content;
		}

		$current_form = function_exists( 'wpcf7_get_current_contact_form' ) ? wpcf7_get_current_contact_form() : null;
		if ( ! $current_form ) {
			return $content;
		}

		// Build list of protected CF7 numeric IDs from stored options
		$options = FormShield::get_options();
		$protected_ids = array();
		if ( isset( $options['formshield_forms'] ) && is_array( $options['formshield_forms'] ) ) {
			foreach ( $options['formshield_forms'] as $stored_form_id => $form_data ) {
				if (
					strpos( $stored_form_id, 'cf7-' ) === 0 &&
					isset( $form_data['form_enabled'] ) && (int) $form_data['form_enabled'] === 1
				) {
					if ( preg_match( '/cf7-(\d+)/', $stored_form_id, $m ) ) {
						$protected_ids[] = (int) $m[1];
					}
				}
			}
		}

		$form_id = (int) $current_form->id();
		if ( empty( $protected_ids ) || ! in_array( $form_id, $protected_ids, true ) ) {
			return $content;
		}

		$badge_html = FormShield::badge_html( 'Contact Form 7' );
		if ( empty( $badge_html ) ) {
			return $content;
		}

		// Append badge after the form HTML
		return $content . $badge_html;
	}
	
	/**
	 * Add JavaScript to inject badge into CF7 forms
	 */
	public static function add_cf7_badge_script() {
		// Check if we should show the badge
		if ( !FormShield::should_show_badge() ) {
			return;
		}
		
		// Get options
		$options = FormShield::get_options();
		
		// Build protected forms array
		$protected_forms = array();
		if (isset($options['formshield_forms'])) {
			foreach ($options['formshield_forms'] as $form_id => $form_data) {
				if (strpos($form_id, 'cf7-') === 0 && isset($form_data['form_enabled']) && $form_data['form_enabled']) {
					// Get the numeric part of the form ID
					$matches = array();
					if (preg_match('/cf7-(\d+)/', $form_id, $matches)) {
						$numeric_id = $matches[1];
						$protected_forms[] = $numeric_id;
					}
				}
			}
		}
		
		// Return if no CF7 forms are protected
		if (empty($protected_forms)) {
			return;
		}
		
		// Get badge HTML
		$badge_html = FormShield::badge_html( 'Contact Form 7' );
		
		if ( !$badge_html ) {
			return;
		}
		
		// Add filter to modify form output
		add_filter('wpcf7_form_elements', function($content) use ($protected_forms, $badge_html) {
			// Get current form ID
			$current_form = wpcf7_get_current_contact_form();
			if (!$current_form) {
				return $content;
			}
			
			$form_id = $current_form->id();
			
			// Check if this form is protected
			if (in_array($form_id, $protected_forms)) {
				// Add badge after the form
				$content .= $badge_html;
			}
			
			return $content;
		});
	}

}

add_action( 'plugins_loaded', function() { new FormShieldCF7Integration(); });
