<?php
namespace SabaiApps\Directories\Component\Notification\Event;

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

class PostPublishedEvent extends AbstractEntityEvent {

	protected $_paramEntityStatus = 'publish';

	protected function _notificationEntityEventInfo() {
		return array(
			'label'            => _x( 'Post published', 'notification event', 'directories-pro' ) . ' - %s',
			'default_settings' => array(
				'new_only'         => false,
				'was_pending_only' => true,
				'ignore_backend'   => true,
			),
			'actions'          => array(
				'entity_entity_published',
			),
			'weight'           => 6,
			'testable'         => true,
		);
	}

	public function notificationEventSettingsForm( array $settings, array $parents = array() ) {
		// Fix for both options turned on for some reason on certain occasion
		if ( ! empty( $settings['new_only'] )
			&& ! empty( $settings['was_pending_only'] )
		) {
			$settings['was_pending_only'] = false;
		}
		$form  = parent::notificationEventSettingsForm( $settings, $parents );
		$form += array(
			'new_only'         => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Newly created posts only', 'directories-pro' ),
				'#default_value' => ! empty( $settings['new_only'] ),
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						sprintf( '[name="%s"]', $this->_application->Form_Form_fieldName( array_merge( $parents, array( 'was_pending_only' ) ) ) ) => array(
							'type'  => 'checked',
							'value' => false,
						),
					),
				),
			),
			'was_pending_only' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Previously pending posts only', 'directories-pro' ),
				'#default_value' => ! empty( $settings['was_pending_only'] ),
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						sprintf( '[name="%s"]', $this->_application->Form_Form_fieldName( array_merge( $parents, array( 'new_only' ) ) ) ) => array(
							'type'  => 'checked',
							'value' => false,
						),
					),
				),
			),
			'ignore_backend'   => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Ignore backend submissions', 'directories-pro' ),
				'#default_value' => ! empty( $settings['ignore_backend'] ),
				'#horizontal'    => true,
			),
		);
		return $form;
	}

	public function notificationEventMessages( array $settings, array $params ) {
		// Ignore new submissions from backend?
		if ( $this->_application->getPlatform()->isAdmin()
			&& ( ! isset( $settings['ignore_backend'] ) || $settings['ignore_backend'] )
			&& ! isset( $params[1] ) // is new submission?
		) {
			return;
		}

		if ( ! isset( $params[0] )
			|| ! $params[0] instanceof IEntity
		) {
			throw new Exception\RuntimeException( 'Invalid entity.' );
		}

		$entity = $params[0];
		if ( ! $this->_isBundleEnabled( $entity, $settings ) ) {
			return;
		}

		if ( ! empty( $settings['new_only'] ) ) {
			if ( isset( $params[1] ) ) {
				return; // old entity exists
			}
		} elseif ( ! empty( $settings['was_pending_only'] ) ) {
			if ( ! isset( $params[1] )
				|| ! $params[1] instanceof IEntity
				|| ! $params[1]->isPending()
			) {
				return; // old entity was not pending
			}
		}

		return array( array( 'entity' => $entity ) );
	}

	protected function _getDefaultNotificationLabel() {
		return sprintf( __( 'Your %1$s has been published', 'directories-pro' ), strtolower( $singular = $this->_getContentTypeLabel() ), $singular );
	}

	protected function _getDefaultNotificationBody() {
		return array(
			sprintf( __( 'The following %1$s that you have submitted has been published.', 'directories-pro' ), strtolower( $singular = $this->_getContentTypeLabel() ), $singular ),
			'%title%' . PHP_EOL . '%permalink_url%',
		);
	}

	public function notificationEventParamSettingsForm( array $settings, array $parents = array() ) {
		return array(
			'entity' => array(
				'#title'                 => ( $bundle = $this->_isSingleContentType( $settings ) ) ? $bundle->getLabel( 'singular' ) : $this->_application->Entity_BundleTypeInfo( $this->_bundleType, 'label_singular' ),
				'#type'                  => 'autocomplete',
				'#select2'               => true,
				'#select2_ajax'          => true,
				'#select2_ajax_url'      => $this->_getQueryEntitiesUrl( $settings ),
				'#select2_item_text_key' => 'title',
				'#horizontal'            => true,
				'#element_validate'      => array(
					function ( Form $form, &$value, $element ) {
						if ( ! $entity = $this->_application->Entity_Entity( 'post', $value ) ) {
							$form->setError( 'Invalid entity.', $element );
							return;
						}
						if ( ! $entity->isPublished() ) {
							$form->setError( __( 'You must select a published post.', 'directories-pro' ), $element );
						}
					},
				),
			),
		);
	}

	public function notificationEventParams( array $settings, array $paramSettings ) {
		$params = array( '_action' => 'entity_entity_published' );
		if ( ! $entity = $this->_application->Entity_Entity( 'post', $paramSettings['entity'] ) ) {
			throw new Exception\RuntimeException( 'Failed fetching post. ID: ' . $paramSettings['entity'] );
		}
		$params[0] = $entity;
		if ( ! empty( $settings['was_pending_only'] ) ) {
			$params[1] = clone $entity;
			$params[1]->setStatus( $this->_application->Entity_Status( $entity->getType(), 'pending' ) );
		}
		return $params;
	}
}
