<?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 );
					// Get current form entries
					$entries = 	wpFluent()
						            ->table('fluentform_submissions')
						            ->where('form_id', $form->id)
						            ->where('status', '!=', 'trashed')
						            ->get();
					// Get last entry date
					$last_entry_obj = array_pop($entries);
					$last_entry    = is_object($last_entry_obj) ? $last_entry_obj->created_at : null;
					// Push to forms list
					$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, count( $entries ) ),
						'activity'    => FormShieldForms::get_latest_form_activity( $fid, $form->updated_at )
					);
				}
			}
			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 ) {
		// If HP protection enabled, validate the form
		$options = form_shield()->get_options();
		$fid     = self::get_form_id( absint( $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 ) {
				// If the detection check fails, prevent the form submission and display an error message.
				$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 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(); });
