<?php
namespace SabaiApps\Directories\Component\Notification\Helper;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Request;

class SettingsFormHelper {

	public function help( Application $application, $route ) {
		$notifications = $application->getModel( 'Notification', 'Notification' )->fetch( 0, 0, 'name', 'ASC' );
		if ( ! $notifications->count() ) {
			return array();
		}

		// Load scripts for modal form
		$application->Form_Scripts( array( 'slider' ) );
		$application->getPlatform()->loadJqueryUiJs( array( 'effects-highlight' ) );

		$admin_notifications_path = rtrim( $route, '/' );
		$form                     = array(
			'add_notification' => array(
				'#type'  => 'markup',
				'#value' => '<div class="' . DRTS_BS_PREFIX . 'float-end">' . $application->LinkTo(
					__( 'Add Notification', 'directories-pro' ),
					$application->Url( $admin_notifications_path . '/add' ),
					array(
						'no_escape' => true,
						'icon'      => 'fas fa-plus',
						'container' => 'modal',
						'modalSize' => 'xl',
						'cache'     => 'drts-notification-add-notification',
					),
					array(
						'class' => DRTS_BS_PREFIX . 'btn ' . DRTS_BS_PREFIX . 'btn-success',
						'rel'   => 'sabaitooltip',
						// 'title' => __('Edit Notification', 'directories-pro'),
					)
				) . '</div>',
			),
			'notifications'    => array(
				'#type'           => 'tableselect',
				'#disabled'       => true,
				'#multiple'       => true,
				'#js_select'      => true,
				'#class'          => 'drts-data-table drts-notification-admin-notifications',
				'#header'         => array(
					'name'   => ucwords( __( 'Notification name', 'directories-pro' ) ),
					'event'  => __( 'Notification event', 'directories-pro' ),
					'method' => ucwords( __( 'Notification method', 'directories-pro' ) ),
					'status' => __( 'Status', 'directories-pro' ),
					'links'  => '',
				),
				'#row_attributes' => array(
					'@all' => array(
						'method' => array(
							'style' => 'width:40%;',
						),
						'links'  => array(
							'style' => 'white-space:nowrap;text-align:' . ( $application->getPlatform()->isRtl() ? 'left' : 'right' ) . ';',
						),
					),
				),
				'#js_ready'       => array(
					'var params = {}; params[DRTS.params.ajax] = "#drts-modal"; 
                    $.get("' . $application->Url( $admin_notifications_path . '/add', array(), '', '&' ) . '", params, function (_data) {
                        DRTS.cache("drts-notification-add-notification", _data);
                    });',
				),
			),
		);
		if ( isset( $directory ) ) {
			unset( $form['notifications']['#header']['directory'] );
		}

		foreach ( $notifications as $notification ) {
			if ( ! $event = $application->Notification_Services_event( $notification->event, true ) ) {
				continue;
			}
			if ( ! $event->notificationEventIsEnabled() ) {
				continue;
			}

			$event_label   = $application->H( $event->notificationEventInfo( 'label' ) );
			$sender_labels = array();
			if ( ! empty( $notification->data['sender'] ) ) {
				foreach ( array_keys( $notification->data['sender'] ) as $sender_name ) {
					if ( $sender = $application->Notification_Services_sender( $sender_name, true ) ) {
						$sender_label    = $application->H( $sender->notificationSenderInfo( 'label' ) );
						$sender_settings = empty( $notification->data['sender'][ $sender_name ] ) ? array() : $notification->data['sender'][ $sender_name ];
						if ( $sender_recipients = $sender->notificationSenderRecipientList( $sender_settings ) ) {
							$sender_label = sprintf( __( '%1$s (%2$s)' ), $sender_label, implode( ', ', $sender_recipients ) );
						}
						$sender_labels[] = $application->H( $sender_label );
					} else {
						$sender_labels[] = '<span class="' . DRTS_BS_PREFIX . 'text-danger">' . $application->H( $sender_name ) . '</span>';
					}
				}
			}
			$links = array(
				$application->LinkTo(
					'',
					$application->Url( $admin_notifications_path . '/' . $notification->id ),
					array(
						'no_escape' => true,
						'icon'      => 'fas fa-cog',
						'container' => 'modal',
						'modalSize' => 'xl',
					),
					array(
						'class'            => DRTS_BS_PREFIX . 'btn ' . DRTS_BS_PREFIX . 'btn-outline-secondary',
						'data-modal-title' => __( 'Edit Notification', 'directories-pro' ) . ' - ' . $notification->getLabel(),
						'rel'              => 'sabaitooltip',
						'title'            => __( 'Edit Notification', 'directories-pro' ),
					)
				),
			);
			if ( ! $notification->system ) {
				$links[] = $application->LinkTo(
					'',
					$application->Url( $admin_notifications_path . '/' . $notification->id . '/delete' ),
					array(
						'no_escape' => true,
						'icon'      => 'fas fa-trash-can',
						'container' => 'modal',
						'modalSize' => 'lg',
					),
					array(
						'class'            => DRTS_BS_PREFIX . 'btn ' . DRTS_BS_PREFIX . 'btn-outline-danger',
						'data-modal-title' => __( 'Delete Notification', 'directories-pro' ) . ' - ' . $notification->getLabel(),
						'rel'              => 'sabaitooltip',
						'title'            => __( 'Delete Notification', 'directories-pro' ),
					)
				);
			}
			$form['notifications']['#options'][ $notification->id ] = array(
				'name'   => $application->H( isset( $notification->data['label'] ) ? $notification->data['label'] : $event_label ),
				'event'  => $event_label,
				'method' => implode( ', ', $sender_labels ),
				'status' => '<span role="button" class="drts-action-button drts-notification-set-status ' . DRTS_BS_PREFIX . 'text-' . ( $notification->active ? 'success' : 'muted' ) . '"'
					. ' data-action-url="' . $application->Url( $admin_notifications_path . '/set_status', array(), '', '&' ) . '"'
					. ' data-action-token="' . $application->Form_Form_createToken( 'notification_admin_notifications', 1800, true ) . '"'
					. ' data-action-data-id="' . $notification->id . '"'
					. ' title="' . $application->H( $notification->active ? __( 'Active', 'directories-pro' ) : __( 'Inactive', 'directories-pro' ) ) . '">'
					. '<i class="fas fa-check-circle fa-xl"></i></span>',
				'links'  => implode( PHP_EOL, $links ),
				'_meta'  => array(
					'weight' => $event->notificationEventInfo( 'weight' ),
					'label'  => $event->notificationEventInfo( 'label' ),
					'system' => $notification->system,
				),
			);
		}
		uasort(
			$form['notifications']['#options'],
			function ( $a, $b ) {
				if ( $a['_meta']['weight'] < $b['_meta']['weight'] ) {
					return -1;
				}
				if ( $a['_meta']['weight'] === $b['_meta']['weight'] ) {
					if ( 0 === $res = strcasecmp( $a['_meta']['label'], $b['_meta']['label'] ) ) {
						$res = $a['_meta']['system'] > $b['_meta']['system'] ? -1 : 1;
					}
					return $res;
				}
				return 1;
			}
		);

		return $form;
	}

	public function sender( Application $application, $senderName, array $settings = array(), array $messageMeta = array(), array $parents = array(), ?array $trigger = null ) {
		if ( ! $sender = $application->Notification_Services_sender( $senderName, true ) ) {
			return;
		}

		$default_settings = (array) $sender->notificationSenderInfo( 'default_settings' );
		$settings        += $default_settings;
		foreach ( array_keys( $default_settings ) as $setting_key ) {
			if ( is_array( $default_settings[ $setting_key ] ) ) {
				$settings[ $setting_key ] += $default_settings[ $setting_key ];
			}
		}
		if ( false === $settings_form = $sender->notificationSenderSettingsForm( $settings, $messageMeta, $parents, array( 'settings' ) ) ) {
			return;
		}

		if ( ! empty( $messageMeta['recipients'] )
			&& ! isset( $settings_form['recipients']['event'] )
			&& ( $event_recipient_types = $sender->notificationSenderInfo( 'event_recipient_types' ) )
		) {
			$event_recipient_options = array();
			foreach ( $messageMeta['recipients'] as $recipient_name => $recipient ) {
				if ( ! is_array( $recipient ) ) {
					$recipient = array(
						'type'  => $recipient_name,
						'label' => $recipient,
					);
				}
				if ( isset( $recipient['type'] )
					&& in_array( $recipient['type'], $event_recipient_types )
				) {
					$event_recipient_options[ $recipient_name ] = $recipient['label'];
				}
			}
			if ( ! empty( $event_recipient_options ) ) {
				$settings_form['recipients']['event'] = array(
					'#disable_select_all' => true,
					'#type'               => 'checkboxes',
					'#options'            => $event_recipient_options,
					'#default_value'      => $settings['recipients']['event'],
					'#weight'             => 1,
					'#class'              => DRTS_BS_PREFIX . 'mb-n1',
				);
			}
		}

		if ( isset( $trigger ) ) {
			foreach ( array_keys( $settings_form ) as $setting_name ) {
				if ( strpos( $setting_name, '#' ) === 0 ) {
					continue;
				}

				if ( ! empty( $settings_form[ $setting_name ]['#required'] )
					&& $settings_form[ $setting_name ]['#required'] === true
				) {
					$settings_form[ $setting_name ]['#required'] = function ( $form ) use ( $trigger ) {
						return (bool) $form->getValue( $trigger );
					};
				}
			}
		}

		return $settings_form;
	}
}
