<?php
namespace SabaiApps\Directories\Component\Payment\NotificationEvent;

use SabaiApps\Directories\Component\Payment\IOrder;
use SabaiApps\Directories\Exception;
use SabaiApps\Directories\Component\Notification\Event\AbstractEvent;

abstract class AbstractOrderNotificationEvent extends AbstractEvent {

	public function notificationEventMessageMeta( array $settings ) {
		return array(
			'tags'       => $this->_getOrderTags(),
			'recipients' => array(
				'customer' => array(
					'type'  => 'user',
					'label' => __( 'Order Customer', 'directories-pro' ),
				),
			),
		);
	}

	public function notificationEventMessages( array $settings, array $params ) {
		if ( ! isset( $params[0] )
			|| ! $params[0] instanceof IOrder
		) {
			throw new Exception\RuntimeException( 'Invalid order.' );
		}

		$order = $params[0];
		if ( ! $entity = $this->_application->Entity_Entity( $order->paymentOrderEntityType(), $order->paymentOrderEntityId() ) ) {
			throw new Exception\RuntimeException( 'Could not fetch entity from order.' );
		}

		return array(
			array(
				'entity'     => $entity,
				'tags'       => $this->_getOrderTags( $order ),
				'recipients' => array(
					'customer' => array(
						'type'  => 'user',
						'value' => $order->paymentOrderUserId(),
					),
				),
			),
		);
	}

	protected function _getDefaultNotificationRecipients() {
		if ( $this->_isForAdmin ) {
			return parent::_getDefaultNotificationRecipients();
		}

		return array(
			'event' => array( 'customer' ),
		);
	}

	protected function _getOrderTags( ?IOrder $order = null ) {
		if ( ! isset( $order ) ) {
			return array(
				'%order_name%',
				'%order_number%',
				'%order_total%',
				'%order_date%',
				'%order_admin_url%',
				'%order_item_title%',
				'%order_item_permalink%',
			);
		}

		$ret = array(
			'%order_name%'      => $order->paymentOrderName(),
			'%order_number%'    => $order->paymentOrderNumber(),
			'%order_total%'     => strip_tags( $order->paymentOrderTotalHtml() ),
			'%order_date%'      => $this->_application->System_Date( $order->paymentOrderTimestamp() ),
			'%order_admin_url%' => $order->paymentOrderAdminUrl( '&' ),
		);
		if ( $entity = $this->_application->Entity_Entity( $order->paymentOrderEntityType(), $order->paymentOrderEntityId() ) ) {
			$ret['%order_item_title%']     = $entity->getTitle();
			$ret['%order_item_permalink%'] = $entity->isPublished() ? $this->_application->Entity_PermalinkUrl( $entity ) : $ret['%order_admin_url%'];
		} else {
			$this->_application->logError( 'Could not fetch entity from order.' );
			$ret['%order_item_title%'] = $ret['%order_item_permalink%'] = '';
		}

		return $ret;
	}
}
