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

use SabaiApps\Directories\Component\Payment\ISubscription;
use SabaiApps\Directories\Exception;

abstract class AbstractSubscriptionNotificationEvent extends AbstractEntityNotificationEvent {

	protected $_isSubscription = true;

	public function notificationEventMessageMeta( array $settings ) {
		$meta          = parent::notificationEventMessageMeta( $settings );
		$meta['tags'] += $this->_getSubscriptionTags();
		return $meta;
	}

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

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

		if ( ! $this->_isBundleEnabled( $entity, $settings ) ) {
			return;
		}

		return array(
			array(
				'entity' => $entity,
				'tags'   => $this->_getSubscriptionTags( $subscription ),
			),
		);
	}

	protected function _getSubscriptionTags( ?ISubscription $subscription = null ) {
		if ( ! isset( $subscription ) ) {
			return array(
				'%subscription_name%',
				'%subscription_number%',
				'%subscription_total%',
				'%subscription_next_payment_date%',
				'%subscription_admin_url%',
			);
		}

		return array(
			'%subscription_name%'              => $subscription->paymentSubscriptionName(),
			'%subscription_number%'            => $subscription->paymentSubscriptionNumber(),
			'%subscription_total%'             => strip_tags( $subscription->paymentSubscriptionTotalHtml() ),
			'%subscription_next_payment_date%' => ( $next_payment_html = $subscription->paymentSubscriptionNextPaymentHtml() ) ? strip_tags( $next_payment_html ) : '',
			'%subscription_admin_url%'         => $subscription->paymentSubscriptionAdminUrl(),
		);
	}
}
