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

class FormShieldFluentFormsIntegration extends FormShieldIntegration {

	public static $form_prefix = 'flu';

	/*
	 * 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( 'fluentform/validation_errors', array( __CLASS__, 'validate_forms' ), 10, 4 );
		add_action( 'formshield_autoprotect_forms', array( __CLASS__, 'enable_forms' ), 30, 1 );
		
		/**
		 * Add protected badges to Fluent Forms
		 */
		add_action( 'wp_footer', array( __CLASS__, 'add_fluent_badges' ) );
	}

	/**
	 * Get Formidable Forms
	 * This should return the forms list
	 *
	 * @return Array $forms_list
	 */
	public static function get_forms( $forms_list ) {
		if ( function_exists( 'wpFluent' ) ) {
			$additional_forms     = array();
			$form_list = wpFluent()->table('fluentform_forms')->orderBy('created_at', 'DESC')->get();
			if ( is_array( $form_list ) ) {
				foreach ( $form_list as $form ) {
					$fid = self::get_form_id( $form->id );
					// Count entries without loading all rows.
					$entry_count = (int) wpFluent()
						->table('fluentform_submissions')
						->where('form_id', $form->id)
						->where('status', '!=', 'trashed')
						->count();
					// Fetch only the latest entry for the activity timestamp.
					$latest_entry = wpFluent()
						->table('fluentform_submissions')
						->where('form_id', $form->id)
						->where('status', '!=', 'trashed')
						->orderBy('id', 'DESC')
						->first();
					$last_entry = is_object( $latest_entry ) ? $latest_entry->created_at : null;
					$additional_forms[] = array(
						'id'          => $fid,
						'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
						'name'        => $form->title,
						'type'        => 'Fluent Forms',
						'location'    => 'Fluent Forms: ' . $form->title . ' (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 Fluent 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, $form, $fields ) {
		$options = form_shield()->get_options();
		$fid     = self::get_form_id( absint( $form->id ) );
		if ( is_array( $options ) && ! empty( $options['formshield_forms'][ $fid ]['form_enabled'] ) ) {
			// Honeypot check first — same pattern as other integrations.
			$honeypot_filled = ! empty( formshield_get_post_string( 'formshield_honeypot', '' ) );
			if ( ! $honeypot_filled && ! empty( $_POST ) ) {
				foreach ( array_keys( $_POST ) as $key ) {
					if ( strpos( (string) $key, 'fs_hp_' ) === 0 && ! empty( $_POST[ $key ] ) ) {
						$honeypot_filled = true;
						break;
					}
				}
			}
			if ( $honeypot_filled ) {
				FormShieldForms::handle_suspicious_form_activity( $fid );
				$errors['spam'] = FormShieldForms::fail_form_error_message();
			} elseif ( FormShieldForms::fail_form_validation() ) {
				FormShieldForms::handle_suspicious_form_activity( $fid );
				$errors['spam'] = FormShieldForms::fail_form_error_message();
			}
		}

		return $errors;
	}

	/**
	 * Protect Existing Fluent forms
	 */
	public static function enable_forms( $unattended ) {
		if ( class_exists( '\FluentForm\App\Modules\Form\Form' ) ) {
			$form_list = wpFluent()->table('fluentform_forms')->orderBy('created_at', 'DESC')->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 Fluent Forms
	 */
	public static function add_fluent_badges() {
		$options = FormShield::get_options();
		
		if ( ! isset( $options['formshield_forms'] ) ) {
			return;
		}
		
		// Get protected Fluent Forms only
		$protected_fluent_forms = array();
		foreach ( $options['formshield_forms'] as $fid => $form_data ) {
			// Only check Fluent Forms (flu- prefix)
			if ( strpos( $fid, 'flu-' ) === 0 ) {
				
				if ( isset( $form_data['form_enabled'] ) && $form_data['form_enabled'] ) {
					$protected_fluent_forms[] = $fid;
				} else {
				}
			}
		}
		
		
		if ( empty( $protected_fluent_forms ) ) {
			return;
		}
		
		
		// Enqueue badge script
		wp_enqueue_script( 'formshield-fluent-badge', plugins_url( 'js/fluent-forms-badge.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
		
		// Localize script with data
		wp_localize_script( 'formshield-fluent-badge', 'formshieldFluentData', array(
			'protectedForms' => $protected_fluent_forms,
			'badge' => FormShield_Safe::badge_html_for_js( 'Fluent Forms' )
		) );
	}
}

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