<?php
namespace SabaiApps\Directories\Component\Contact\Form;

use SabaiApps\Directories\Component\Entity\Type\IEntity;

class GravityFormForm extends AbstractForm {

	protected function _contactFormInfo() {
		return array(
			'title' => 'Gravity Form',
		);
	}

	public function contactFormIsEnabled() {
		return class_exists( '\GFAPI', false );
	}

	public function contactFormInit() {
		add_filter( 'gform_pre_render', array( $this, 'preRenderFilter' ) );
		add_filter( 'gform_replace_merge_tags', array( $this, 'replaceMergeTagsFilter' ) );
	}

	public function contactFormList() {
		$list = array();
		if ( $gravity_forms = \GFAPI::get_forms() ) {
			foreach ( $gravity_forms as $form ) {
				$list[ $form['id'] ] = $form['title'];
			}
		}
		return $list;
	}

	public function contactFormRender( $formId, IEntity $entity ) {
		return do_shortcode( '[gravityform ajax="true" id="' . intval( $formId ) . '" title="false" description="false"]' );
	}

	public function preRenderFilter( $form ) {
		if ( ( $entity = $this->_isDisplaying() )
			|| ( $entity = $this->_isSending( true ) ) // this becomes true when submission failed because of an error
		) {
			array_push(
				$form['fields'],
				\GF_Fields::create(
					array(
						'type'    => 'html',
						'content' => $this->_getHiddenFieldHtml( $entity ),
					)
				)
			);
		}
		return $form;
	}

	public function replaceMergeTagsFilter( $text ) {
		$tag = '{drts_contact_recipients}';
		if ( strpos( $text, $tag ) !== false ) {
			$text = str_replace( $tag, ( $recipients = $this->_isSending() ) ? implode( ',', $recipients ) : '', $text );
		}
		return $text;
	}
}
