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

if ( class_exists( 'Ninja_Forms' ) && ( version_compare( get_option( 'ninja_forms_version', '0.0.0' ), '3', '<' ) || get_option( 'ninja_forms_load_deprecated', false ) ) ) {

	function formshield_ninja_forms_version_fail() {
		?>
		<div class="notice notice-error is-dismissible">
			<p><?php esc_html_e( 'Ninja Forms version 3 or greater is required. If you have version 3, check to ensure that all of your forms have been converted to version 3.', 'formshield' ); ?></p>
		</div>
		<?php
	}

	add_action( 'admin_notices', 'formshield_ninja_forms_version_fail' );

} else {

	class FormShieldNinjaFormsIntegration extends FormShieldIntegration {
		public static $form_prefix = 'nf';

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

			/**
			 * Auto-protect New Ninja Forms
			 */
			add_action( 'ninja_forms_save_form', array( 'FormShieldAutoProtect', 'init' ), 10, 2 );
			
			/**
			 * Add protected badges to Ninja Forms
			 */
			add_action( 'wp_footer', array( __CLASS__, 'add_ninja_badges' ) );
		}

		/*
		 * Get Ninja Forms
		 * This should return the forms list
		 *
		 * @return Array $forms_list
		 */
		public static function get_forms( $forms_list ) {
			if ( class_exists( 'Ninja_Forms' ) ) {
				$additional_forms = array();
				try {
					$ninja_form_list  = Ninja_Forms()->form()->get_forms();
				} catch (\Exception $e) {
					FormShieldUtils::show_wp_admin_notice( 'Ninja Forms is missing a required function. Check to ensure you have the latest version. <a href="' . esc_url('https://wpsupporting.com/plugins/formshield/') . '">Contact us</a> if the issue persists.' );
					return $forms_list;
				} catch (\Throwable $e) {
					FormShieldUtils::show_wp_admin_notice( 'Ninja Forms is missing a required function. Check to ensure you have the latest version. <a href="' . esc_url('https://wpsupporting.com/plugins/formshield/') . '">Contact us</a> if the issue persists.' );
					return $forms_list;
				}

				if ( is_array( $ninja_form_list ) ) {
					foreach ( $ninja_form_list as $form ) {
						$fid     = self::get_form_id( $form->get_id() );
						$entries = Ninja_Forms()->form( $form->get_id() )->get_subs();
						// get_subs() returns entries ordered newest-first; use reset() to
						// get the first element without depending on its array key.
						$first_entry = ! empty( $entries ) ? reset( $entries ) : null;
						$last_entry  = ( $first_entry && method_exists( $first_entry, 'get_sub_date' ) )
							? $first_entry->get_sub_date( 'Y-m-d H:i:s' )
							: null;
						// Push to forms list
						$additional_forms[] = array(
							'id'          => $fid,
							'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
							'name'        => $form->get_setting( 'title' ),
							'type'        => 'Ninja Forms',
							'location'    => 'Ninja Forms: ' . $form->get_setting( 'title' ) . ' (ID: ' . $form->get_id() . ')',
							'submissions' => FormShieldForms::get_form_submissions_ct( $fid, count( $entries ) ),
							'activity'    => FormShieldForms::get_latest_form_activity( $fid, $form->get_setting( 'date_updated' ) )
						);
					}
				}
				self::prune_disabled_forms( $additional_forms );
				$forms_list = array_merge( $forms_list, $additional_forms );
			}

			return $forms_list;
		}

		/**
		 * Validate Ninja forms
		 *
		 * @param Array $form_data - Array of data from the Ninja Form submitted
		 *
		 * @return Array - $form_data
		 */
		public static function validate_forms( $form_data ) {
			// If HP protection enabled, validate the form
			$options       = form_shield()->get_options();
			$ninja_form_id = $form_data['id'];
			$fid           = self::get_form_id( $ninja_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 ) {
					$fields        = Ninja_Forms()->form( $ninja_form_id )->get_fields();
					$last_field_id = end( $fields )->get_id();
					// Check honeypot first.
					$honeypot_value = formshield_get_post_string( 'formshield_honeypot', '' );
					if ( ! empty( $honeypot_value ) ) {
						FormShieldForms::handle_suspicious_form_activity( $fid );
						$form_data['errors']['fields'][ $last_field_id ] = FormShieldForms::fail_form_error_message();
					} else {
						$validation_failed = FormShieldForms::fail_form_validation();
						if ( $validation_failed ) {
							FormShieldForms::handle_suspicious_form_activity( $fid );
							$form_data['errors']['fields'][ $last_field_id ] = FormShieldForms::fail_form_error_message();
						}
					}
				}
			}

			return $form_data;
		}

		/*
		 * Protect Existing Ninja forms
		 */
		public static function enable_forms( $unattended ) {
			if ( class_exists( 'Ninja_Forms' ) ) {
				try {
					$ninja_form_list  = Ninja_Forms()->form()->get_forms();
				} catch (\Exception $e) {
					FormShieldUtils::show_wp_admin_notice( 'Ninja Forms is missing a required function. Check to ensure you have the latest version. <a href="' . esc_url('https://wpsupporting.com/plugins/formshield/') . '">Contact us</a> if the issue persists.' );
					return;
				} catch (\Throwable $e) {
					FormShieldUtils::show_wp_admin_notice( 'Ninja Forms is missing a required function. Check to ensure you have the latest version. <a href="' . esc_url('https://wpsupporting.com/plugins/formshield/') . '">Contact us</a> if the issue persists.' );
					return;
				}

				if ( is_array( $ninja_form_list ) ) {
					foreach ( $ninja_form_list as $form ) {
						$fid = self::get_form_id( $form->get_id() );
						FormShieldForms::enable_forms( $fid, 1, $unattended );
					}
				}
			}
		}
		
			/**
	 * Add protected badges to Ninja Forms
	 */
	public static function add_ninja_badges() {
		$options = FormShield::get_options();
		
		if ( ! isset( $options['formshield_forms'] ) ) {
			return;
		}
		
		// Get protected Ninja Forms only
		$protected_ninja_forms = array();
		foreach ( $options['formshield_forms'] as $fid => $form_data ) {
			// Only check Ninja Forms (nf- prefix)
			if ( strpos( $fid, 'nf-' ) === 0 ) {
				
				if ( isset( $form_data['form_enabled'] ) && $form_data['form_enabled'] ) {
					$protected_ninja_forms[] = $fid;
				} else {
				}
			}
		}
		
		
		if ( empty( $protected_ninja_forms ) ) {
			return;
		}
		
		// Enqueue badge script
		wp_enqueue_script( 'formshield-ninja-badge', plugins_url( 'js/ninja-forms-badge.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
		
		// Localize script with data
		wp_localize_script( 'formshield-ninja-badge', 'formshieldNinjaFormsData', array(
			'protectedForms' => $protected_ninja_forms,
			'badge' => FormShield_Safe::badge_html_for_js( 'Ninja Forms' )
		) );
	}
	}

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

}
