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

class FormShieldWPFormsIntegration extends FormShieldIntegration {

	public static $form_prefix = 'wpf';

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

		/**
		 * Auto-protect New Forms
		 * After Create - Depends on hpres_autoprotect_scan()
		 * After Duplicate - Depends on hpres_autoprotect_scan()
		 */
		add_action( 'wpforms_create_form', array( 'FormShieldAutoProtect', 'init' ), 10, 0 );
		add_action( 'wpforms_save_form', array( 'FormShieldAutoProtect', 'init' ), 10, 0 );
		
		/**
		 * Add protected badges to WPForms
		 */
		add_action( 'wp_footer', array( __CLASS__, 'add_wpforms_badges' ) );
	}

	/**
	 * Get Forms
	 * This should return the forms list
	 *
	 * @return Array $forms_list
	 */
	public static function get_forms( $forms_list ) {
		if ( function_exists( 'wpforms' ) ) {
			$additional_forms     = array();
			$form_list = wpforms()->form->get();
			if ( is_array( $form_list ) ) {
				foreach ( $form_list as $form ) {
					$fid = self::get_form_id( $form->ID );
					$entry_count = absint( get_post_meta( $form->ID, 'wpforms_entries_count', true ) );
					// Push to forms list
					$additional_forms[] = array(
						'id'          => $fid,
						'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
						'name'        => ( $form->post_title ),
						'type'        => 'WPForms',
						'location'    => 'WPForms: ' . $form->post_title . ' (ID: ' . $form->ID . ')',
						'submissions' => FormShieldForms::get_form_submissions_ct( $fid, $entry_count ),
						'activity'    => FormShieldForms::get_latest_form_activity( $fid, $form->post_modified )
					);
				}
			}
			self::prune_disabled_forms( $additional_forms );
			$forms_list = array_merge( $forms_list, $additional_forms );
		}

		return $forms_list;
	}

	/**
	 * Validate forms
	 *
	 * @param Array $errors - Array of error messages
	 * @param Array $values - Array of form value strings submitted
	 *
	 * @return Array - $errors
	 */
	public static function validate_forms( $errors, $form_data ) {
		// Skip if already has errors
		if ( !empty($errors) ) {
			return $errors;
		}
		
		// If FormShield protection enabled, validate the form
		$options = form_shield()->get_options();
		$fid     = self::get_form_id( absint( $form_data['id'] ) );
		
		if ( is_array( $options ) && array_key_exists( 'formshield_forms', $options ) && isset( $options['formshield_forms'][ $fid ] ) ) {
			$formshield_form_enabled = $options['formshield_forms'][ $fid ]['form_enabled'];
			
			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( $fid );
					$errors[$form_data['id']]['header'] = FormShieldForms::fail_form_error_message();
				} else {
					// Run FormShield validation
					$validation_failed = FormShieldForms::fail_form_validation();
					
					if ( $validation_failed ) {
						// Record suspicious activity
						FormShieldForms::handle_suspicious_form_activity( $fid );
						
						// Get error message
						$errors[$form_data['id']]['header'] = FormShieldForms::fail_form_error_message();
					}
				}
			}
		}

		return $errors;
	}

	/**
	 * Protect Existing forms
	 */
	public static function enable_forms( $unattended ) {
		if ( function_exists( 'wpforms' ) ) {
			$form_list = wpforms()->form->get();
			if ( is_array( $form_list ) ) {
				foreach ( $form_list as $form ) {
					// Assign unique form id
					$fid = self::get_form_id( $form->ID );
					FormShieldForms::enable_forms( $fid, 1, $unattended );
				}
			}
		}
	}
	
	/**
	 * Add protected badges to WPForms
	 */
	public static function add_wpforms_badges() {
		$options = FormShield::get_options();
		
		
		if ( ! isset( $options['formshield_forms'] ) ) {
			return;
		}
		
		// Get protected WPForms
		$protected_wpforms = array();
		foreach ( $options['formshield_forms'] as $fid => $form_data ) {
			if ( strpos( $fid, 'wpf-' ) === 0 && isset( $form_data['form_enabled'] ) && $form_data['form_enabled'] ) {
				$protected_wpforms[] = $fid;
			}
		}
		
		if ( empty( $protected_wpforms ) ) {
			return;
		}
		
		// Enqueue badge script
		wp_enqueue_script( 'formshield-wpforms-badge', plugins_url( 'js/wp-forms-badge.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
		
		// Localize script with data
		wp_localize_script( 'formshield-wpforms-badge', 'formshieldWPFormsData', array(
			'protectedForms' => $protected_wpforms,
			'badge' => FormShield_Safe::badge_html_for_js( 'WPForms' )
		) );
	}
}

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