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

use SabaiApps\Directories\Exception;
use SabaiApps\Framework\User\RegisteredIdentity;
use SabaiApps\Directories\Component\Notification\Event\AbstractEvent;

abstract class AbstractAccountNotificationEvent extends AbstractEvent {

	protected $_isForAdmin = true;

	public function notificationEventMessageMeta( array $settings ) {
		return array(
			'tags' => $this->_getUserTags(),
		);
	}

	public function notificationEventMessages( array $settings, array $params ) {
		$message = array(
			'tags' => $this->_getUserTags( $this->_extractIdentity( $params ) ),
		);
		// Check if any email settings exist in dashboard panel settings
		$account_panel_config = $this->_application->getComponent( 'Dashboard' )->getConfig( 'panel', 'panel_settings', 'account' );
		$name                 = $this->_name;
		if ( strpos( $name, 'dashboard_' ) === 0 ) {
			$name = substr( $name, strlen( 'dashboard_' ) );
		}
		$name .= '_email';
		if ( ! empty( $account_panel_config[ $name ] )
			&& ! empty( $account_panel_config[ $name . '_custom' ] )
		) {
			$message['subject'] = $account_panel_config[ $name . '_subject' ];
			$message['body']    = $account_panel_config[ $name . '_body' ];
		}

		return array( $message );
	}

	protected function _extractIdentity( array $params ) {
		if ( ! isset( $params[0] )
			|| ! $params[0] instanceof RegisteredIdentity
		) {
			throw new Exception\RuntimeException( 'Invalid identity.' );
		}

		return $params[0];
	}

	public function notificationEventParamSettingsForm( array $settings, array $parents = array() ) {
		return array(
			'user' => array(
				'#title'      => __( 'Select user', 'directories-pro' ),
				'#type'       => 'user',
				'#horizontal' => true,
			),
		);
	}

	public function notificationEventParams( array $settings, array $paramSettings ) {
		if ( ! $identity = $this->_application->UserIdentity( $paramSettings['user'] ) ) {
			throw new Exception\RuntimeException( 'Failed fetching user by user ID: ' . $paramSettings['user'] );
		}
		return array( 0 => $identity );
	}
}
