<?php
/**
 * GravityForms
 *
 * @package CommonFrameworkPlugin
 */

namespace CommonFrameworkPlugin;

// use CommonFrameworkPlugin\Utility;
use WP_Query;

/**
 * Adds additional functionality to Gravity forms
 */
class GravityForms extends \CommonFrameworkPlugin\Module {


	/**
	 * Only register if on an admin page and if fieldmanager plugin is active.
	 *
	 * @return bool
	 */
	public function can_register() {
		return true;
	}

	/**
	 * Register our hooks.
	 *
	 * @return void
	 */
	public function register() {
		add_filter( 'gform_filters_get_users', [ $this, 'unlimited_users_dropdown' ] );
		add_filter( 'gform_form_settings_fields', [ $this, 'add_settings_field' ], 20, 2 );
		add_shortcode( 'gform_universal_form_key_display', [ $this, 'gform_universal_form_key_display' ] );
	}

	/**
	 * Filter for unlimited number of users in searchbar for gravity forms
	 *
	 * @param array $args array to be changed
	 *
	 * @return array $args modified $args
	 */
	public function unlimited_users_dropdown( $args ) {
		$args['number'] = -1;
		return $args;
	}

	/**
	 * Adds form options to gravity forms
	 *
	 * @see https://docs.gravityforms.com/gform_form_settings_fields/
	 *
	 * @param array $fields Form Settings fields.
	 * @param array $form   The current form.
	 *
	 * @return array
	 */
	public function add_settings_field( $fields, $form = [] ) {

		$fields['form_options']['fields'][] = array(
			'name'          => 'universal_form_key',
			'type'          => 'text',
			'label'         => esc_html__( 'Universal Form Key' ),
			'description' => 'WARNING : Changing this key will impact functionality on the site.',
			'default_value' => null,
		);

		return $fields;
	}

	/**
	 * Prints out the form that has the matching universal_form_key field
	 *
	 * @param string $atts match the gravity forms parameters and are used to customize the form output
	 * @return array $the correct gform or a spit out of if the form is not found
	 */
	public function gform_universal_form_key_display( $atts ) {
		$atts = shortcode_atts(
			array(
				'universal_form_key' => false,
				'title' => false,
				'description' => false,
			),
			$atts,
			'gform_universal_form_key_display'
		);

		if ( ! $atts['universal_form_key'] ) {
			return 'Please provide a universal_form_key';
		}

		$all_forms = \GFAPI::get_forms();

		// TODOD check the potential 200 form limit issue

		foreach ( $all_forms as $form ) {
			if ( rgar( $form, 'universal_form_key', false ) == $atts['universal_form_key'] ) {
				return do_shortcode( '[gravityform id="' . rgar( $form, 'id' ) . '" title="' . var_export( $atts['title'], true ) . '" description="' . var_export( $atts['description'], true ) . '"]' );
			}
		}
		return 'No form found with provided Universal Form Key.';
	}
}
