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

class FormShieldHappyFormsIntegration extends FormShieldIntegration {

	public static $form_prefix = 'hpf';

	/*
	 * 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( 'happyforms_validate_submission', array( __CLASS__, 'validate_forms' ), 10, 3 );
		add_action( 'formshield_autoprotect_forms', array( __CLASS__, 'enable_forms' ), 30, 1 );
		// add_filter( 'happyforms_is_registered', function() {return true;}, 10, 1 );
		
		/**
		 * Add protected badges to Happy Forms
		 */
		add_action( 'wp_footer', array( __CLASS__, 'add_happy_badges' ) );
	}

	/**
	 * Get Forms
	 * This should return the forms list
	 *
	 * @return Array $forms_list
	 */
	public static function get_forms( $forms_list ) {
		if ( function_exists( 'HappyForms' ) ) {
			$additional_forms     = array();
			$form_list = happyforms_get_form_controller()->get();
			if ( is_array( $form_list ) ) {
				foreach ( $form_list as $form ) {
					$fid = self::get_form_id( $form['ID'] );
					// $entry_count = absint( get_post_meta( $form['ID'], 'wpforms_entries_count', true ) );
					if ( function_exists( 'happyforms_get_message_controller' ) && is_callable( array( 'HappyForms_Message_Controller', 'get_by_form' ) ) ) {
						$entries = happyforms_get_message_controller()->get_by_form( $form['ID'] );
						if( $entries ) {
							$entry_count = count($entries);
							$updated = $entries[0]['post_modified'];
						}
					} else {
						$entry_count = 0;
						$updated = $form['updated_at'];
					}
					// Push to forms list
					$additional_forms[] = array(
						'id'          => $fid,
						'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
						'name'        => $form['post_title'],
						'type'        => 'Happy Forms',
						'location'    => 'Happy Forms: ' . $form['post_title'] . ' (ID: ' . $form['ID'] . ')',
						'submissions' => FormShieldForms::get_form_submissions_ct( $fid, $entry_count ),
						'activity'    => FormShieldForms::get_latest_form_activity( $fid, $updated )
					);
				}
			}
			self::prune_disabled_forms( $additional_forms );
			$forms_list = array_merge( $forms_list, $additional_forms );
		}

		return $forms_list;
	}

	/**
	 * Validate forms
	 *
	 * @param Bool $is_valid
	 * @param Array $request - Array of form value strings submitted
	 * @param Array $form - Form object
	 *
	 * @return Bool - valid?
	 */
	public static function validate_forms( $is_valid, $request, &$form ) {
		// Skip if already invalid
		if ( !$is_valid ) {
			return $is_valid;
		}
		
		// If FormShield 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 ) {
				// 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 );
					$is_valid = false;
					
					// Add error message
					$session = happyforms_get_session();
					$session->add_error( $form['ID'], html_entity_decode( FormShieldForms::fail_form_error_message() ) );
				} else {
					// Run FormShield validation
					$validation_failed = FormShieldForms::fail_form_validation();
					
					if ( $validation_failed ) {
						$is_valid = false;
						
						// Record suspicious activity
						FormShieldForms::handle_suspicious_form_activity( $fid );
						
						// Add error message
						$session = happyforms_get_session();
						$session->add_error( $form['ID'], html_entity_decode( FormShieldForms::fail_form_error_message() ) );
					}
				}
			}
		}

		return $is_valid;
	}

	/**
	 * Protect Existing forms
	 */
	public static function enable_forms( $unattended ) {
		if ( function_exists( 'HappyForms' ) ) {
			$form_list = happyforms_get_form_controller()->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 Happy Forms
	 */
	public static function add_happy_badges() {
		$options = FormShield::get_options();
		
		if ( ! isset( $options['formshield_forms'] ) ) {
			return;
		}
		
		// Get protected Happy Forms
		$protected_happy_forms = array();
		foreach ( $options['formshield_forms'] as $fid => $form_data ) {
			if ( strpos( $fid, 'hpf-' ) === 0 && isset( $form_data['form_enabled'] ) && $form_data['form_enabled'] ) {
				$protected_happy_forms[] = $fid;
			}
		}
		
		if ( empty( $protected_happy_forms ) ) {
			return;
		}
		
		// Enqueue badge script
		wp_enqueue_script( 'formshield-happy-badge', plugins_url( 'js/happy-forms-badge.js', dirname(__FILE__) ), array('jquery'), FORMSHIELD_VERSION, true );
		
		// Localize script with data
		wp_localize_script( 'formshield-happy-badge', 'formshieldHappyFormsData', array(
			'protectedForms' => $protected_happy_forms,
			'badge' => FormShield_Safe::badge_html_for_js( 'Happy Forms' )
		) );
	}
}

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