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

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Form;

class SettingsFormHelper {

	public function help( Application $application, array $config, array $parents ) {
		$form                    = array();
		$guest_field_name_prefix = $application->Form_Form_fieldName( array_merge( $parents, array( 'guest' ) ) );
		$form['guest']           = array(
			'#weight'       => 30,
			'#title'        => __( 'Guest Post Settings', 'directories-pro' ),
			'#tree'         => true,
			'collect_name'  => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Collect guest name', 'directories-pro' ),
				'#default_value' => ! isset( $config['guest']['collect_name'] ) || ! empty( $config['guest']['collect_name'] ),
				'#weight'        => 1,
				'#horizontal'    => true,
			),
			'require_name'  => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Require guest name', 'directories-pro' ),
				'#default_value' => ! isset( $config['guest']['require_name'] ) || ! empty( $config['guest']['require_name'] ),
				'#weight'        => 3,
				'#states'        => array(
					'visible' => array(
						'input[name="' . $guest_field_name_prefix . '[collect_name]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#horizontal'    => true,
			),
			'collect_email' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Collect e-mail address', 'directories-pro' ),
				'#default_value' => ! empty( $config['guest']['collect_email'] ),
				'#weight'        => 5,
				'#horizontal'    => true,
			),
			'require_email' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Require e-mail address', 'directories-pro' ),
				'#default_value' => ! empty( $config['guest']['require_email'] ),
				'#weight'        => 6,
				'#states'        => array(
					'visible' => array(
						'input[name="' . $guest_field_name_prefix . '[collect_email]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#horizontal'    => true,
			),
			'check_exists'  => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Do not allow e-mail address used by registered users', 'directories-pro' ),
				'#default_value' => ! empty( $config['guest']['check_exists'] ),
				'#weight'        => 7,
				'#states'        => array(
					'visible' => array(
						'input[name="' . $guest_field_name_prefix . '[collect_email]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#horizontal'    => true,
			),
			'collect_url'   => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Collect website URL', 'directories-pro' ),
				'#default_value' => ! empty( $config['guest']['collect_url'] ),
				'#weight'        => 10,
				'#horizontal'    => true,
			),
			'require_url'   => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Require website URL', 'directories-pro' ),
				'#default_value' => ! empty( $config['guest']['require_url'] ),
				'#weight'        => 11,
				'#states'        => array(
					'visible' => array(
						'input[name="' . $guest_field_name_prefix . '[collect_url]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#horizontal'    => true,
			),
		);
		if ( $application->System_Util_canCheckMx() ) {
			$form['guest']['check_mx'] = array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Check MX record of e-mail address', 'directories-pro' ),
				'#default_value' => ! empty( $config['guest']['check_mx'] ),
				'#weight'        => 8,
				'#states'        => array(
					'visible' => array(
						'input[name="' . $guest_field_name_prefix . '[collect_email]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#horizontal'    => true,
			);
		}
		$form['guest']['collect_privacy'] = array(
			'#type'          => 'checkbox',
			'#title'         => __( 'Add a privacy policy consent checkbox', 'directories-pro' ),
			'#default_value' => ! empty( $config['guest']['collect_privacy'] ),
			'#weight'        => 15,
			'#horizontal'    => true,
		);

		$lost_pass_default_email = $application->FrontendSubmit_LostPassword_defaultEmail();
		$form['login']           = array(
			'#weight'                 => 10,
			'#title'                  => __( 'User Login Settings', 'directories-pro' ),
			'#tree'                   => true,
			'#element_validate'       => array(
				function ( Form\Form $form, &$value, $element ) {
					if ( empty( $value['allow_username'] )
					&& empty( $value['allow_email'] )
						) {
						$value['allow_username'] = true;
					}
				},
			),
			'form'                    => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Show custom user login form', 'directories-pro' ),
				'#default_value' => ! isset( $config['login']['form'] ) || ! empty( $config['login']['form'] ),
				'#horizontal'    => true,
				'#weight'        => 1,
			),
			'allow_username'          => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Allow login with username', 'directories-pro' ),
				'#default_value' => ! isset( $config['login']['allow_username'] ) || ! empty( $config['login']['allow_username'] ),
				'#horizontal'    => true,
				'#weight'        => 2,
				'#states'        => array(
					'visible' => array(
						$login_form_selector = 'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'login', 'form' ) ) ) . '"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'allow_email'             => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Allow login with e-mail address', 'directories-pro' ),
				'#default_value' => ! empty( $config['login']['allow_email'] ),
				'#horizontal'    => true,
				'#weight'        => 3,
				'#states'        => array(
					'visible' => array(
						$login_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'lost_pass_link'          => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Show lost password link', 'directories-pro' ),
				'#default_value' => ! isset( $config['login']['lost_pass_link'] ) || ! empty( $config['login']['lost_pass_link'] ),
				'#horizontal'    => true,
				'#weight'        => 5,
				'#states'        => array(
					'visible' => array(
						$login_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'lost_pass_custom_email'  => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Customize lost password e-mail', 'directories-pro' ),
				'#horizontal'    => true,
				'#default_value' => ! empty( $config['login']['lost_pass_custom_email'] ),
				'#states'        => array(
					'visible' => array(
						$login_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
						$lost_pass_link_selector = 'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'login' ) ) ) . '[lost_pass_link]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#weight'        => 6,
			),
			'lost_pass_email_subject' => array(
				'#type'                  => 'textfield',
				'#field_prefix'          => __( 'E-mail subject', 'directories-pro' ),
				'#description'           => $lost_pass_email_tags  = $application->System_Util_availableTags( $application->FrontendSubmit_LostPassword_emailTags() ),
				'#description_no_escape' => true,
				'#horizontal'            => true,
				'#default_value'         => empty( $config['login']['lost_pass_email_subject'] ) ? $lost_pass_default_email[0] : $config['login']['lost_pass_email_subject'],
				'#states'                => array(
					'visible' => array(
						$login_form_selector     => array(
							'type'  => 'checked',
							'value' => true,
						),
						$lost_pass_link_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
						$lost_pass_custom_email_selector = 'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'login' ) ) ) . '[lost_pass_custom_email]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#weight'                => 7,
			),
			'lost_pass_email_body'    => array(
				'#type'                  => 'textarea',
				'#description'           => $lost_pass_email_tags,
				'#description_no_escape' => true,
				'#horizontal'            => true,
				'#default_value'         => empty( $config['login']['lost_pass_email_body'] ) ? $lost_pass_default_email[1] : $config['login']['lost_pass_email_body'],
				'#rows'                  => count( explode( PHP_EOL, $lost_pass_default_email[1] ) ),
				'#states'                => array(
					'visible' => array(
						$login_form_selector             => array(
							'type'  => 'checked',
							'value' => true,
						),
						$lost_pass_link_selector         => array(
							'type'  => 'checked',
							'value' => true,
						),
						$lost_pass_custom_email_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#weight'                => 8,
			),
		);

		// Social login settings
		if ( $oauth_settings_form = $application->FrontendSubmit_Oauth_settingsForm( isset( $config['login']['oauth'] ) ? $config['login']['oauth'] : array(), array_merge( $parents, array( 'login', 'oauth' ) ) ) ) {
			$form['login']['oauth'] = array(
				'#weight' => 60,
				'#states' => array(
					'visible' => array(
						$login_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			) + $oauth_settings_form;
		}

		if ( $application->getPlatform()->isLoginFormRequired() ) {
			$form['login']['form']['#type']  = 'hidden';
			$form['login']['form']['#value'] = true;
		}

		$verify_account_default_email = $application->FrontendSubmit_VerifyAccount_defaultEmail();
		$form['register']             = array(
			'#weight'                 => 20,
			'#title'                  => __( 'User Registration Settings', 'directories-pro' ),
			'#tree'                   => true,
			'form'                    => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Show custom user registration form', 'directories-pro' ),
				'#default_value' => ! isset( $config['register']['form'] ) || ! empty( $config['register']['form'] ),
				'#horizontal'    => true,
				'#weight'        => 3,
			),
			'show_link'               => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Show user registration link', 'directories-pro' ),
				'#default_value' => ! empty( $config['register']['show_link'] ),
				'#weight'        => 5,
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						$register_form_selector = 'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'register' ) ) ) . '[form]"]' => array(
							'type'  => 'checked',
							'value' => false,
						),
					),
				),
			),
			'show_separate_page'      => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Show user registration form on separate page', 'directories-pro' ),
				'#default_value' => ! empty( $config['register']['show_separate_page'] ),
				'#description'   => sprintf(
					__( 'If enabled, the user registration page URL will be %s.', 'directories-pro' ),
					$application->MainUrl( '/' . $application->getComponent( 'FrontendSubmit' )->getSlug( 'login' ) . '/register' )
				),
				'#weight'        => 7,
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						$register_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'show_separate_page_link' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Show user registration link', 'directories-pro' ),
				'#default_value' => ! empty( $config['register']['show_separate_page_link'] ),
				'#weight'        => 7,
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						$register_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
						'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'register' ) ) ) . '[show_separate_page]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'privacy'                 => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Add a privacy policy consent checkbox', 'directories-pro' ),
				'#default_value' => ! empty( $config['register']['privacy'] ),
				'#weight'        => 10,
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						$register_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'verify_email'            => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Enable e-mail verification', 'directories-pro' ),
				'#default_value' => ! empty( $config['register']['verify_email'] ),
				'#weight'        => 60,
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						$register_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			),
			'verify_email_settings'   => array(
				'#title'            => __( 'Email verification settings', 'directories-pro' ),
				'#class'            => 'drts-form-label-lg',
				'#weight'           => 60,
				'#states'           => array(
					'visible' => array(
						$register_form_selector => array(
							'type'  => 'checked',
							'value' => true,
						),
						'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'register' ) ) ) . '[verify_email]"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'custom_email'      => array(
					'#type'          => 'checkbox',
					'#title'         => __( 'Customize verification e-mail', 'directories-pro' ),
					'#horizontal'    => true,
					'#default_value' => ! empty( $config['register']['verify_email_settings']['custom_email'] ),
				),
				'email_subject'     => array(
					'#type'                  => 'textfield',
					'#field_prefix'          => __( 'E-mail subject', 'directories-pro' ),
					'#description'           => $verify_account_email_tags = $application->System_Util_availableTags( $application->FrontendSubmit_VerifyAccount_emailTags() ),
					'#description_no_escape' => true,
					'#horizontal'            => true,
					'#default_value'         => empty( $config['register']['verify_email_settings']['email_subject'] ) ? $verify_account_default_email[0] : $config['register']['verify_email_settings']['email_subject'],
					'#states'                => array(
						'visible' => array(
							$custom_email_selector = 'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'register', 'verify_email_settings' ) ) ) . '[custom_email]"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				),
				'email_body'        => array(
					'#type'                  => 'textarea',
					'#description'           => $verify_account_email_tags,
					'#description_no_escape' => true,
					'#horizontal'            => true,
					'#default_value'         => $email_body = empty( $config['register']['verify_email_settings']['email_body'] ) ? $verify_account_default_email[1] : $config['register']['verify_email_settings']['email_body'],
					'#rows'                  => ( 5 < $rows = count( explode( PHP_EOL, $email_body ) ) ) ? $rows : 5,
					'#states'                => array(
						'visible' => array(
							$custom_email_selector => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				),
				'check_domain'      => array(
					'#type'          => 'checkbox',
					'#title'         => __( 'Blacklist or whitelist e-mail domains', 'directories-pro' ),
					'#horizontal'    => true,
					'#default_value' => ! empty( $config['register']['verify_email_settings']['check_domain'] ),
				),
				'check_domain_type' => array(
					'#type'          => 'select',
					'#options'       => array(
						'blacklist' => __( 'Blacklist', 'directories-pro' ),
						'whitelist' => __( 'Whitelist', 'directories-pro' ),
					),
					'#horizontal'    => true,
					'#default_value' => isset( $config['register']['verify_email_settings']['check_domain_type'] ) ? $config['register']['verify_email_settings']['check_domain_type'] : 'blacklist',
					'#states'        => array(
						'visible' => array(
							$check_domain_selector = 'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'register', 'verify_email_settings' ) ) ) . '[check_domain]"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				),
				'domains'           => array(
					'#type'          => 'textarea',
					'#description'   => __( 'Enter one domain per line. You can also use "*" and "?" wildcard characters.', 'directories-pro' ),
					'#placeholder'   => implode( "\r\n", array( 'user@domain.com', '*@domain.com', 'user?@*.com' ) ),
					'#horizontal'    => true,
					'#default_value' => isset( $config['register']['verify_email_settings']['domains'] ) ? $config['register']['verify_email_settings']['domains'] : null,
					'#rows'          => 3,
					'#states'        => array(
						'visible' => array(
							$check_domain_selector => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				),
				'delete'            => array(
					'#type'          => 'checkbox',
					'#title'         => __( 'Delete unverified users after X days', 'directories-pro' ),
					'#horizontal'    => true,
					'#default_value' => ! empty( $config['register']['verify_email_settings']['delete'] ),
				),
				'delete_after'      => array(
					'#type'          => 'slider',
					'#horizontal'    => true,
					'#default_value' => isset( $config['register']['verify_email_settings']['delete_after'] ) ? $config['register']['verify_email_settings']['delete_after'] : 30,
					'#integer'       => true,
					'#min_value'     => 1,
					'#max_value'     => 50,
					'#field_suffix'  => __( 'day(s)', 'directories-pro' ),
					'#states'        => array(
						'visible' => array(
							'input[name="' . $application->Form_Form_fieldName( array_merge( $parents, array( 'register', 'verify_email_settings' ) ) ) . '[delete]"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				),
			),
		);

		if ( $application->getPlatform()->isRegisterFormRequired() ) {
			$form['register']['form']['#type']  = 'hidden';
			$form['register']['form']['#value'] = true;
		}

		if ( $restrictors = $application->FrontendSubmit_Restrictors() ) {
			$bundles = array();
			foreach ( $application->getModel( 'Directory', 'Directory' )->fetch( 0, 0, array( 'directory_type', 'directory_name' ), array( 'ASC', 'ASC' ) ) as $directory ) {
				foreach ( $application->Entity_Bundles_sort( null, $directory->name ) as $bundle ) {
					$info = $application->Entity_BundleTypeInfo( $bundle );
					if ( empty( $info['frontendsubmit_enable'] ) ) {
						continue;
					}

					$bundles[ $bundle->name ] = $bundle;
				}
			}
			if ( ! empty( $bundles ) ) {
				$bundle_labels = array();
				foreach ( array_keys( $bundles ) as $bundle_name ) {
					$bundle                        = $bundles[ $bundle_name ];
					$bundle_labels[ $bundle_name ] = $bundle->getGroupLabel() . ' - ' . $bundle->getLabel( 'singular' );
					if ( ! empty( $bundle->info['parent'] )
						&& ( $parent_bundle = $application->Entity_Bundle( $bundle->info['parent'] ) )
					) {
						$bundle_labels[ $bundle_name ] = sprintf(
							__( '%1$s (per %2$s)', 'directories-pro' ),
							$bundle_labels[ $bundle_name ],
							$parent_bundle->getLabel( 'singular' )
						);
					}
				}
				unset( $bundles );
				$form['restrict'] = array(
					'#weight' => 40,
					'#title'  => __( 'Submission Restriction Settings', 'directories-pro' ),
					'#tree'   => true,
					'type'    => array(
						'#type'          => 'select',
						'#title'         => __( 'Restriction type', 'directories-pro' ),
						'#options'       => array( '' => __( '— Select —', 'directories-pro' ) ),
						'#horizontal'    => true,
						'#default_value' => isset( $config['restrict']['type'] ) ? $config['restrict']['type'] : '',
					),
				);
				$type_field_name  = $application->Form_Form_fieldName( array_merge( $parents, array( 'restrict', 'type' ) ) );
				foreach ( array_keys( $restrictors ) as $restrictor_name ) {
					if ( ! $restrictor = $application->FrontendSubmit_Restrictors_impl( $restrictor_name, true ) ) {
						continue;
					}

					$form['restrict']['type']['#options'][ $restrictor_name ] = $restrictor->frontendsubmitRestrictorInfo( 'label' );
					if ( ! $restrictor->frontendsubmitRestrictorEnabled() ) {
						$form['restrict']['type']['#options_disabled'][] = $restrictor_name;
						continue;
					}
					$form['restrict']['settings'][ $restrictor_name ]            = $restrictor->frontendsubmitRestrictorSettingsForm(
						$bundle_labels,
						isset( $config['restrict']['settings'][ $restrictor_name ] ) ? $config['restrict']['settings'][ $restrictor_name ] : array(),
						array_merge( $parents, array( 'restrict', 'settings', $restrictor_name ) )
					);
					$form['restrict']['settings'][ $restrictor_name ]['#states'] = array(
						'visible' => array(
							'select[name="' . $type_field_name . '"]' => array( 'value' => $restrictor_name ),
						),
					);
				}
			}
		}

		if ( $application->getComponent( 'FrontendSubmit' )->isLoginDisabled() ) {
			$form['login']['warning'] = $form['register']['warning'] = $form['guest']['warning'] = array(
				array(
					'#weight' => -1,
					'#type'   => 'item',
					'#markup' => '<div class="' . DRTS_BS_PREFIX . 'alert ' . DRTS_BS_PREFIX . 'alert-warning">'
						. $application->H( __( 'The following settings have no effect since login/registration features are disabled.', 'directories-pro' ) )
						. '</div>',
				),
			);
		} elseif ( ! $application->Filter( 'frontendsubmit_redirect_guest', true ) ) {
			$form['guest']['warning'] = array(
				array(
					'#weight' => -1,
					'#type'   => 'item',
					'#markup' => '<div class="' . DRTS_BS_PREFIX . 'alert ' . DRTS_BS_PREFIX . 'alert-warning">'
						. $application->H( __( 'The following settings have no effect because guest redirection to the login/registration page is disabled.', 'directories-pro' ) )
						. '</div>',
				),
			);
		}

		return $application->Filter( 'frontendsubmit_settings_form', $form, array( $config, $parents ) );
	}
}
