<?php
namespace SabaiApps\Directories\Component\Notification\Controller\Admin;

use SabaiApps\Directories\Context;
use SabaiApps\Directories\Component\Form;

class AddNotification extends Form\AbstractMultiStepController {

	protected function _getSteps( Context $context, array &$formStorage ) {
		return array(
			'general_settings' => array(),
			'sender_settings'  => array(),
		);
	}

	public function _getFormForStepGeneralSettings( Context $context, array &$formStorage ) {
		$events        = $event_settings_form = $current_event_settings = array();
		$current_event = $current_label = null;
		if ( $notification = $this->_getNotification( $context ) ) {
			$current_event          = $notification->event;
			$current_label          = $notification->data['label'];
			$current_event_settings = isset( $notification->data['event'] ) ? (array) $notification->data['event'] : array();
		}

		foreach ( array_keys( $this->Notification_Services_events() ) as $event_name ) {
			if ( ! $event = $this->Notification_Services_event( $event_name, true ) ) {
				continue;
			}
			if ( ! $event->notificationEventIsEnabled() ) {
				continue;
			}

			$events[ $event_name ] = $event->notificationEventInfo( 'label' );
			$event_settings        = $current_event === $event_name ? $current_event_settings : array();
			$event_settings       += (array) $event->notificationEventInfo( 'default_settings' );
			if ( $_event_settings_form = $event->notificationEventSettingsForm( $event_settings, array( 'event_settings', $event_name ) ) ) {
				$event_settings_form[ $event_name ]            = $_event_settings_form;
				$event_settings_form[ $event_name ]['#states'] = array(
					'visible' => array(
						'[name="event"]' => array( 'value' => $event_name ),
					),
				);
			}
		}

		return array(
			'#tree'          => true,
			'event'          => array(
				'#title'         => __( 'Notification type', 'directories-pro' ),
				'#type'          => 'select',
				'#options'       => $events,
				'#horizontal'    => true,
				'#required'      => true,
				'#default_value' => $current_event,
			),
			'label'          => array(
				'#type'          => 'textfield',
				'#title'         => __( 'Notification admin label', 'directories-pro' ),
				'#description'   => __( 'Enter a label for administrative purposes only. The default label will be used if none is entered.', 'directories-pro' ),
				'#max_length'    => 255,
				'#horizontal'    => true,
				'#default_value' => $current_label,
			),
			'event_settings' => $event_settings_form,
		);
	}

	public function _getFormForStepSenderSettings( Context $context, array &$formStorage ) {
		$settings   = $formStorage['values']['general_settings'];
		$event_name = $settings['event'];
		$event      = $this->Notification_Services_event( $event_name );

		if ( $notification = $this->_getNotification( $context ) ) {
			$current_settings = (array) $notification->data['sender'];
			$btn_label        = __( 'Save Changes', 'directories-pro' );
			$btn_color        = 'primary';
		} else {
			$event_data       = $event->notificationEventDefaultNotificationData();
			$current_settings = isset( $event_data[0]['sender'] ) ? $event_data[0]['sender'] : array();
			$btn_label        = __( 'Add Notification', 'directories-pro' );
			$btn_color        = 'success';
		}

		$this->_submitButtons[ $context->currentStep ] = array(
			'#btn_label' => $btn_label,
			'#btn_color' => $btn_color,
			'#btn_size'  => 'lg',
		);

		// Get event specific tags
		$event_settings         = empty( $settings['event_settings'][ $event_name ] ) ? array() : $settings['event_settings'][ $event_name ];
		$message_meta           = $event->notificationEventMessageMeta( $event_settings ) + array(
			'tags'       => array(),
			'recipients' => array(),
		);
		$message_meta['tags'][] = '%dashboard_url%';
		$message_meta['tags']   = array_unique( $message_meta['tags'] );

		$form = array();
		foreach ( array_keys( $this->Notification_Services( 'sender' ) ) as $sender_name ) {
			if ( ! $sender = $this->Notification_Services_sender( $sender_name, true, false ) ) {
				continue;
			}

			$label                = $sender->notificationSenderInfo( 'label' );
			$form[ $sender_name ] = array(
				'#tree'            => true,
				'#title'           => '<span class="' . DRTS_BS_PREFIX . 'fw-lighter">' . $this->H( __( 'Notification method: ', 'directories-pro' ) ) . '</span>' . $this->H( $label ),
				'#title_no_escape' => true,
				'#class'           => 'drts-form-label-lg',
				'enable'           => array(
					'#type'          => 'checkbox',
					'#title'         => sprintf( __( 'Enable this notification method', 'directories-pro' ), $label ),
					'#horizontal'    => true,
					'#default_value' => isset( $current_settings[ $sender_name ] ),
				),
			);
			$settings             = empty( $current_settings[ $sender_name ] ) ? array() : $current_settings[ $sender_name ];
			if ( $settings_form = $this->Notification_SettingsForm_sender( $sender_name, $settings, $message_meta, array( $sender_name, 'settings' ), array( $sender_name, 'enable' ) ) ) {
				$form[ $sender_name ]['settings'] = array(
					'#horizontal' => true,
					'#states'     => array(
						'visible' => array(
							'[name="' . $sender_name . '[enable]"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				) + $settings_form;
			}
		}

		return $form;
	}

	protected function _complete( Context $context, array $formStorage ) {
		$general_settings = $formStorage['values']['general_settings'];
		$sender_settings  = $formStorage['values']['sender_settings'];
		unset( $general_settings['directory_name'], $sender_settings['directory_name'] );
		if ( ! empty( $sender_settings ) ) {
			foreach ( array_keys( $sender_settings ) as $sender_name ) {
				if ( empty( $sender_settings[ $sender_name ]['enable'] ) ) {
					unset( $sender_settings[ $sender_name ] );
					continue;
				}

				$sender_settings[ $sender_name ] = isset( $sender_settings[ $sender_name ]['settings'] ) ? $sender_settings[ $sender_name ]['settings'] : array();
			}
		}

		$event_name = $general_settings['event'];
		$event      = $this->Notification_Services_event( $event_name );
		$is_new     = false;
		if ( ! $notification = $this->_getNotification( $context ) ) {
			$notification         = $this->getModel( 'Notification', 'Notification' )->create()->markNew();
			$notification->active = 1;
			$is_new               = true;
		}
		$notification->event = $event_name;
		$notification->data  = array(
			'label'  => isset( $general_settings['label'] ) && strlen( $general_settings['label'] = trim( $general_settings['label'] ) )
				? $general_settings['label']
				: $event->notificationEventDefaultNotificationData()[0]['label'],
			'event'  => isset( $general_settings['event_settings'][ $event_name ] ) ? $general_settings['event_settings'][ $event_name ] : array(),
			'sender' => $sender_settings,
		);
		$notification->commit();

		// Clear action to event map cache
		$this->getPlatform()->deleteCache( 'notification_action_event_map' );

		$context->setSuccess( $this->_getSuccessUrl( $context ) );
		if ( $is_new ) {
			$context->addFlash(
				sprintf(
					__( 'Notification "%s" has been added successfully.', 'directories-pro' ),
					$this->H( $notification->data['label'] )
				)
			);
		}
	}

	protected function _getNotification( Context $context ) {}

	protected function _getSuccessUrl( Context $context ) {
		return $this->Url( '/directories/settings', array( '_drts_form_current_tab' => 'Notification' ) );
	}
}
