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

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

class ContactForm7Form extends AbstractForm {

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

	public function contactFormIsEnabled() {
		return defined( 'WPCF7_VERSION' );
	}

	public function contactFormInit() {
		add_filter( 'wpcf7_form_hidden_fields', array( $this, 'formHiddenFieldsFilter' ) );
		add_filter( 'wpcf7_mail_components', array( $this, 'mailComponentsFilter' ) );
		// Need to manually populate values for post special mail tags as they work when the form is inside the post content only.
		add_filter( 'wpcf7_special_mail_tags', array( $this, 'specialMailTagsFilter' ), 10, 3 );
	}

	public function contactFormList() {
		$list = array();
		if ( $wpcf7_forms = get_posts(
			array(
				'post_type'      => 'wpcf7_contact_form',
				'post_status'    => 'publish',
				'posts_per_page' => -1,
			)
		) ) {
			foreach ( $wpcf7_forms as $post ) {
				$list[ $post->ID ] = $post->post_title;
			}
		}
		return $list;
	}

	public function contactFormRender( $formId, IEntity $entity ) {
		if ( $post_id = intval( $formId ) ) {
			return do_shortcode( '[contact-form-7 id="' . $this->_maybeGetTranslatedPostId( $post_id, 'wpcf7_contact_form' ) . '"]' );
		}
	}

	public function formHiddenFieldsFilter( $fields ) {
		if ( $entity = $this->_isDisplaying() ) {
			$fields[ self::PARAM_HIDDEN ] = $entity->getId();
		}
		return $fields;
	}

	public function mailComponentsFilter( $components ) {
		if ( $recipients = $this->_isSending() ) {
			$components['recipient'] = implode( ',', $recipients );
		}
		return $components;
	}

	public function specialMailTagsFilter( $output, $name, $html ) {
		if ( strpos( $name, '_post_' ) === 0
			&& ( $entity = $this->_isSending( true ) )
			&& ( $post = $entity->post() )
		) {
			switch ( $name ) {
				case '_post_id':
					return (string) $post->ID;
				case '_post_name':
					return $post->post_name;
				case '_post_title':
					return $html ? esc_html( $post->post_title ) : $post->post_title;
				case '_post_url':
					return get_permalink( $post->ID );
				case '_post_author':
				case '_post_author_email':
					$user = new \WP_User( $post->post_author );
					return $name === '_post_author' ? $user->display_name : $user->user_email;
			}
		}
		return $output;
	}
}
