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

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Notification\Event\AbstractEntityEvent;
use SabaiApps\Directories\Component\Notification\Event\EntityEventMessageIterator;

abstract class AbstractEntityNotificationEvent extends AbstractEntityEvent {

	protected $_isSubscription = false;

	protected function _isEventBundle( Bundle $bundle ) {
		return parent::_isEventBundle( $bundle )
			&& ! empty( $bundle->info['payment_enable'] );
	}

	public function notificationEventMessageMeta( array $settings ) {
		$meta = parent::notificationEventMessageMeta( $settings );
		if ( ! $this->_isSubscription ) {
			$meta['tags'][] = '%payment_expire_days%';
			$meta['tags'][] = '%payment_expire_on%';
			$meta['tags'][] = '%payment_renew_grace_period%';
		}

		return $meta;
	}

	protected function _getMessageIterator( array $entities, array $settings ) {
		return new EntityNotificationEventMessageIterator(
			$entities,
			$settings,
			$this->_application->getComponent( 'Payment' )->getConfig( 'plan', 'grace_period_days' ),
			function ( $timestamp ) {
				return $this->_application->System_Date( $timestamp ); },
			function ( $entity ) use ( $settings ) {
				return $this->_isBundleEnabled( $entity, $settings ); }
		);
	}
}

class EntityNotificationEventMessageIterator extends EntityEventMessageIterator {

	protected $_gracePeriodDays, $_dateFunc, $_isEnabledFunc;

	public function __construct( array $entities, array $settings, $gracePeriodDays, $dateFunc, $isEnabledFund ) {
		parent::__construct( $entities, $settings );
		$this->_gracePeriodDays = $gracePeriodDays;
		$this->_dateFunc        = $dateFunc;
		$this->_isEnabledFunc   = $isEnabledFund;
	}

	protected function _isEntityValid( IEntity $entity ) {
		return call_user_func( $this->_isEnabledFunc, $entity );
	}

	protected function _getEntityMessage( IEntity $entity ) {
		$payment_plan = $entity->getSingleFieldValue( 'payment_plan' );
		return array(
			'tags' => array(
				'%payment_expire_days%'        => empty( $payment_plan['expires_at'] ) ? '' : ( ( $days = floor( ( $payment_plan['expires_at'] - time() ) / 86400 ) ) ? $days : 1 ),
				'%payment_expire_on%'          => empty( $payment_plan['expires_at'] ) ? '' : call_user_func( $this->_dateFunc, $payment_plan['expires_at'] ),
				'%payment_renew_grace_period%' => $this->_gracePeriodDays,
			),
		);
	}
}
