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

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Display\Model\Element;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Display\Helper\RenderHelper;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

abstract class AbstractForm implements IForm {

	const PARAM_HIDDEN = '_drts_contact_entity_id';
	protected $_application, $_name, $_info;

	public function __construct( Application $application, $name ) {
		$this->_application = $application;
		$this->_name        = $name;
	}

	public function contactFormInfo( $key = null ) {
		if ( ! isset( $this->_info ) ) {
			$this->_info = $this->_contactFormInfo();
		}
		return isset( $key ) ? ( isset( $this->_info[ $key ] ) ? $this->_info[ $key ] : null ) : $this->_info;
	}

	/**
	 * @return array
	 */
	abstract protected function _contactFormInfo();

	protected function _isDisplaying() {
		return ( ( $entity = $this->_getDisplayedEntity() )
			&& ! $entity->isTaxonomyTerm()
			&& RenderHelper::isRendering( $entity->getBundleName(), 'detailed' )
			&& $this->_application->Contact_Forms_isEnabled( $entity )
		) ? $entity : false;
	}

	protected function _getDisplayedEntity() {
		if ( isset( $GLOBALS['drts_entity'] ) ) {
			return $GLOBALS['drts_entity'];
		}

		return $this->_application->Filter( 'contact_form_current_entity', null );
	}

	protected function _isSending( $returnEntity = false ) {
		if ( ! $entity = $this->_getSendingEntity() ) {
			return false;
		}

		if ( $returnEntity ) {
			return $entity;
		}

		return ( $recipients = $this->_application->Contact_Forms_recipients( $entity ) ) ? $recipients : false;
	}

	/**
	 * @return IEntity|null
	 */
	protected function _getSendingEntity() {
		if ( empty( $_POST[ self::PARAM_HIDDEN ] )
			|| ( ! $entity = $this->_application->Entity_Entity( 'post', $_POST[ self::PARAM_HIDDEN ] ) )
			|| $entity->isTaxonomyTerm()
		) {
			return;
		}

		return $entity;
	}

	protected function _maybeGetTranslatedPostId( $id, $bundleName ) {
		$id = intval( $id );
		if ( ( $lang = $this->_application->getPlatform()->getCurrentLanguage() )
			&& ( $translated_entity_id = $this->_application->getPlatform()->getTranslatedId( 'post', $bundleName, $id, $lang ) )
		) {
			$id = $translated_entity_id;
		}
		return $id;
	}

	protected function _getHiddenFieldHtml( IEntity $entity ) {
		return '<input type="hidden" name="' . self::PARAM_HIDDEN . '" value="' . intval( $entity->getId() ) . '" />';
	}

	public function contactFormOnDisplayElementSaved( $formId, Bundle $bundle, Element $element ) {}
	public function contactFormOnDisplayElementRemoved( $formId, Bundle $bundle, array $settings, $elementName, $elementId ) {}
}
