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

class FormShieldFormidableFormsIntegration extends FormShieldIntegration {

	public static $form_prefix = 'frm';

	/*
	 * 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( 'frm_validate_entry', array( __CLASS__, 'validate_forms' ), 10, 2 );
		add_action( 'formshield_autoprotect_forms', array( __CLASS__, 'enable_forms' ), 30, 1 );

		/**
		 * Auto-protect New Formidable Forms
		 * After Create - Depends on hpres_autoprotect_scan()
		 * After Duplicate - Depends on hpres_autoprotect_scan()
		 */
		add_action( 'frm_update_form', array( 'FormShieldAutoProtect', 'init' ), 10, 2 );
		add_action( 'frm_after_duplicate_form', array( 'FormShieldAutoProtect', 'init' ), 10, 2 );
		
		/**
		 * Add protected badges to Formidable Forms
		 */
		add_action( 'wp_footer', array( __CLASS__, 'add_formidable_badges' ) );
	}

	/**
	 * Get Formidable Forms
	 * This should return the forms list
	 *
	 * @return Array $forms_list
	 */
	public static function get_forms( $forms_list ) {
		if ( is_callable( 'FrmAppHelper::plugin_version' ) ) {
			$additional_forms     = array();
			$formidable_form_list = FrmForm::get_published_forms();
			if ( is_array( $formidable_form_list ) ) {
				foreach ( $formidable_form_list as $form ) {
					$fid = self::get_form_id( $form->id );
					// Count entries without loading all rows.
					$entry_count = method_exists( 'FrmEntry', 'count_entries' )
						? (int) FrmEntry::count_entries( array( 'form_id' => $form->id ) )
						: 0;
					// Fetch only the latest entry for the activity timestamp.
					$latest_entries = FrmEntry::getAll(
						array( 'it.form_id' => $form->id ),
						'ORDER BY id DESC',
						'1'
					);
					$last_entry_obj = ! empty( $latest_entries ) ? reset( $latest_entries ) : null;
					$last_entry     = ( $last_entry_obj && isset( $last_entry_obj->created_at ) )
						? $last_entry_obj->created_at
						: null;
					// Push to forms list
					$additional_forms[] = array(
						'id'          => $fid,
						'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
						'name'        => $form->name,
						'type'        => 'Formidable Forms',
						'location'    => 'Formidable Forms: ' . $form->name . ' (ID: ' . $form->id . ')',
						'submissions' => FormShieldForms::get_form_submissions_ct( $fid, $entry_count ),
						'activity'    => FormShieldForms::get_latest_form_activity( $fid, $last_entry )
					);
				}
			}
			self::prune_disabled_forms( $additional_forms );
			$forms_list = array_merge( $forms_list, $additional_forms );
		}

		return $forms_list;
	}

	/**
	 * Validate Formidable 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, $values ) {
		// 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( $values['form_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['spam'] = 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['spam'] = FormShieldForms::fail_form_error_message();
					}
				}
			}
		}

		return $errors;
	}

	/**
	 * Protect Existing Formidable forms
	 */
	public static function enable_forms( $unattended ) {
		if ( is_callable( 'FrmAppHelper::plugin_version' ) ) {
			$formidable_form_list = FrmForm::get_published_forms();
			if ( is_array( $formidable_form_list ) ) {
				foreach ( $formidable_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 Formidable Forms
	 */
	public static function add_formidable_badges() {
		$options = FormShield::get_options();
		
		if ( ! isset( $options['formshield_forms'] ) ) {
			return;
		}
		
		// Get protected Formidable Forms
		$protected_formidable_forms = array();
		foreach ( $options['formshield_forms'] as $fid => $form_data ) {
			if ( strpos( $fid, 'frm-' ) === 0 && isset( $form_data['form_enabled'] ) && $form_data['form_enabled'] ) {
				$protected_formidable_forms[] = $fid;
			}
		}
		
		if ( empty( $protected_formidable_forms ) ) {
			return;
		}
		
		// Enqueue badge script
		wp_enqueue_script( 'formshield-formidable-badge', plugins_url( 'js/formidable-forms-badge.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
		
		// Localize script with data
		wp_localize_script( 'formshield-formidable-badge', 'formshieldFormidableData', array(
			'protectedForms' => $protected_formidable_forms,
			'badge' => FormShield_Safe::badge_html_for_js( 'Formidable Forms' )
		) );
	}
}

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