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

class FormShieldElementorFormsIntegration extends FormShieldIntegration {

	public static $form_prefix = 'elf';

	/*
	 * This is where you will add filters and actions
	 */
	public function __construct() {
		add_filter( 'formshield_forms_list', array( __CLASS__, 'get_forms' ), 30, 1 );
		add_action( 'elementor_pro/forms/validation', array( __CLASS__, 'validate_forms' ), 10, 2 );
		add_action( 'formshield_autoprotect_forms', array( __CLASS__, 'enable_forms' ), 30, 1 );
		
		/**
		 * Add protected badges to Elementor Forms
		 */
		add_action( 'wp_footer', array( __CLASS__, 'add_elementor_badges' ) );
	}

	/**
	 * Get Formidable Forms
	 * This should return the forms list
	 *
	 * @return Array $forms_list
	 */
	public static function get_forms( $forms_list ) {
		if ( function_exists( '_is_elementor_installed' ) && defined( 'ELEMENTOR_PRO_VERSION' ) ) {
			$additional_forms     = array();
			try {
				$submissions = (new ElementorPro\Modules\Forms\Submissions\Database\Query())->get_submissions();
			} catch (\Exception $e) {
				$submissions = [];
			} catch (\Throwable $e) {
				$submissions = [];
			}
			$form_list = [
				array(
					'id' => 'all', 
					'name' => 'All Elementor Forms', 
					'entries' => $submissions,
					'updated_at' => '',
				),
			];
			foreach ( $form_list as $form ) {
				$fid       = self::get_form_id( $form['id'] );
				$form_name = isset( $form['name'] ) ? $form['name'] : 'All Elementor Forms';
				$additional_forms[] = array(
					'id'          => $fid,
					'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
					'name'        => $form_name,
					'type'        => 'Elementor Form',
					'location'    => 'Elementor Form: ' . $form_name,
					'submissions' => FormShieldForms::get_form_submissions_ct( $fid, 0 ),
					'activity'    => FormShieldForms::get_latest_form_activity( $fid, '' ),
				);
			}
			self::prune_disabled_forms( $additional_forms );
			$forms_list = array_merge( $forms_list, $additional_forms );
		}

		return $forms_list;
	}

	/**
	 * Validate Formidable forms
	 *
	 * @param Object $record - Form Record object
	 * @param Object $ajax_handler - Ajax Handler object
	 *
	 */
	public static function validate_forms( $record, $ajax_handler ) {
		// If HP protection enabled, validate the form
		$options = form_shield()->get_options();
		$fid     = self::get_form_id( 'all' );
		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 ) {
				$field_id = 0;
				$fields   = $record->get( 'fields' );
				if ( is_array( $fields ) && ! empty( $fields ) ) {
					$field_id = $fields[0]['id'];
				}
				// Check honeypot first.
				$honeypot_value = formshield_get_post_string( 'formshield_honeypot', '' );
				if ( ! empty( $honeypot_value ) ) {
					FormShieldForms::handle_suspicious_form_activity( $fid );
					$ajax_handler->add_error( $field_id, FormShieldForms::fail_form_error_message() );
					$ajax_handler->add_error_message( FormShieldForms::fail_form_error_message() );
				} else {
					$validation_failed = FormShieldForms::fail_form_validation();
					if ( $validation_failed ) {
						FormShieldForms::handle_suspicious_form_activity( $fid );
						$ajax_handler->add_error( $field_id, FormShieldForms::fail_form_error_message() );
						$ajax_handler->add_error_message( FormShieldForms::fail_form_error_message() );
					}
				}
			}
		}

	}

	/**
	 * Protect Existing Formidable forms
	 */
	public static function enable_forms( $unattended ) {
		if ( function_exists( '_is_elementor_installed' ) && defined( 'ELEMENTOR_PRO_VERSION' ) ) {
			$form_list = [['id' => 'all']];
			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 Elementor Forms
	 */
	public static function add_elementor_badges() {
		$options = FormShield::get_options();
		
		if ( ! isset( $options['formshield_forms'] ) ) {
			return;
		}
		
		// Get protected Elementor Forms
		$protected_elementor_forms = array();
		foreach ( $options['formshield_forms'] as $fid => $form_data ) {
			if ( strpos( $fid, 'elf-' ) === 0 && isset( $form_data['form_enabled'] ) && $form_data['form_enabled'] ) {
				$protected_elementor_forms[] = $fid;
			}
		}
		
		if ( empty( $protected_elementor_forms ) ) {
			return;
		}
		
		// Enqueue badge script
		wp_enqueue_script( 'formshield-elementor-badge', plugins_url( 'js/elementor-forms-badge.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
		
		// Localize script with data
		wp_localize_script( 'formshield-elementor-badge', 'formshieldElementorData', array(
			'protectedForms' => $protected_elementor_forms,
			'badge' => FormShield_Safe::badge_html_for_js( 'Elementor Forms' )
		) );
	}
}

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