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

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Context;
use SabaiApps\Directories\Component\System;
use SabaiApps\Directories\Component\Form;

class Edit extends System\Controller\Admin\AbstractSettings {

	protected function _getSettingsForm( Context $context, array &$formStorage ) {
		if ( $context->getRequest()->asBool( 'show_settings' ) ) {
			return array(
				'settings' => array(
					'#type'   => 'markup',
					'#markup' => '<pre>' . var_export( $context->bundle->info, true ) . '</pre>',
				),
			);
		}

		// Add label settings
		$info = $this->Entity_BundleTypeInfo( $context->bundle );
		$form = array(
			'#tabs'      => array(
				'general' => array(
					'#title'  => __( 'General', 'directories-pro' ),
					'#weight' => -1,
				),
			),
			'#tab_style' => 'pill_less_margin',
			'#validate'  => array(
				array( array( $this, '_validate' ), array( $context->bundle ) ),
			),
			'general'    => array(
				'#tab'   => 'general',
				'#tree'  => false,
				'labels' => array( '#weight' => 1 ) + $this->_getLabelSettingsForm( $context->bundle, $info ),
			),
		);
		if ( $context->bundle->entitytype_name === 'post' ) {
			$form['general']['labels']['label_author'] = array(
				'#type'          => 'textfield',
				'#title'         => __( 'Author label', 'directories-pro' ),
				'#default_value' => ( $label = $context->bundle->getLabel( 'author' ) ) ? $label : __( 'Author', 'directories-pro' ),
				'#horizontal'    => true,
				'#placeholder'   => is_string( $info['label_author'] ) ? $info['label_author'] : __( 'Author', 'directories-pro' ),
				'#required'      => true,
			);
		}
		if ( ! empty( $info['public'] )
			&& ! empty( $info['slug'] )
		) {
			$form['seo']['single'] = array(
				'#title'  => __( 'Permalink Settings', 'directories-pro' ),
				'#weight' => 10,
				'#tree'   => false,
			);
			if ( empty( $info['parent'] )
				&& empty( $info['parent_field'] )
			) {
				if ( ! empty( $context->bundle->info['is_taxonomy'] ) ) {
					$paths = array( '%slug%' );
					if ( ! empty( $context->bundle->info['is_hierarchical'] ) ) {
						$paths[] = '%parent_term%/%slug%';
					}
				} else {
					$paths = array( '%id%', '%slug%' );
					if ( ! empty( $context->bundle->info['taxonomies'] ) ) {
						foreach ( array_keys( $context->bundle->info['taxonomies'] ) as $taxonomy_type ) {
							$paths[] = '%' . $taxonomy_type . '%/%id%';
							$paths[] = '%' . $taxonomy_type . '%/%slug%';
						}
					}
				}
				$page_slug                          = $this->getComponent( $context->bundle->component )->getSlug( $context->bundle->group );
				$form['seo']['single']['permalink'] = array(
					'#title'      => __( 'Permalink structure', 'directories-pro' ),
					'#type'       => 'item',
					'#markup'     => '<div class="' . DRTS_BS_PREFIX . 'd-flex ' . DRTS_BS_PREFIX . 'flex-row ' . DRTS_BS_PREFIX . 'align-items-center"><span class="' . DRTS_BS_PREFIX . 'text-nowrap ' . DRTS_BS_PREFIX . 'me-1">' . rtrim( $this->getPlatform()->getMainUrl(), '/' ) . '/' . $this->H( $page_slug ) . '/</span>
<input class="' . DRTS_BS_PREFIX . 'form-control" name="slug" type="text" size="20" value="' . $this->H( $context->bundle->info['slug'] ) . '" />
<span class="' . DRTS_BS_PREFIX . 'text-nowrap ' . DRTS_BS_PREFIX . 'mx-1">/</span>
<select class="' . DRTS_BS_PREFIX . 'form-select" name="permalink_path">' . implode( PHP_EOL, $this->_pathsToOptions( $context->bundle, $paths ) ) . '</select></div>',
					'#horizontal' => true,
					'#weight'     => 3,
				);
				if ( ! empty( $context->bundle->info['is_primary'] )
					&& $context->bundle->entitytype_name === 'post'
				) {
					$form['seo']['single']['permalink_type'] = array(
						'#title'         => $form['seo']['single']['permalink']['#title'],
						'#type'          => 'select',
						'#options'       => array(
							'hierarchical' => __( 'Hierarchical', 'directories-pro' ),
							'flat'         => __( 'Flat', 'directories-pro' ),
							'114compat'    => __( 'v1.14 compatible', 'directories-pro' ),
						),
						'#default_value' => $context->bundle->info['permalink_type'] ?? 'hierarchical',
						'#horizontal'    => true,
						'#weight'        => 2,
					);
					unset( $form['seo']['single']['permalink']['#title'] );
					$form['seo']['single']['permalink']['#states'] = array(
						'visible' => array(
							'[name="permalink_type"]' => array( 'value' => 'hierarchical' ),
						),
					);
					$form['seo']['single']['permalink_flat']       = array(
						'#type'       => 'item',
						'#markup'     => '<div class="' . DRTS_BS_PREFIX . 'd-flex ' . DRTS_BS_PREFIX . 'flex-row ' . DRTS_BS_PREFIX . 'align-items-center"><span class="' . DRTS_BS_PREFIX . 'text-nowrap ' . DRTS_BS_PREFIX . 'me-1">' . rtrim( $this->getPlatform()->getMainUrl(), '/' ) . '/' . $this->H( $page_slug ) . '/</span>
<select class="' . DRTS_BS_PREFIX . 'form-select" name="permalink_flat_path">' . implode( PHP_EOL, $this->_pathsToOptions( $context->bundle, array( '%slug%', '%id%' ) ) ) . '</select></div>',
						'#horizontal' => true,
						'#weight'     => 3,
						'#states'     => array(
							'visible' => array(
								'[name="permalink_type"]' => array( 'value' => 'flat' ),
							),
						),
					);
					$form['seo']['single']['permalink_114compat']  = array(
						'#type'       => 'item',
						'#markup'     => '<div class="' . DRTS_BS_PREFIX . 'd-flex ' . DRTS_BS_PREFIX . 'flex-row ' . DRTS_BS_PREFIX . 'align-items-center"><span class="' . DRTS_BS_PREFIX . 'text-nowrap ' . DRTS_BS_PREFIX . 'me-1">' . rtrim( $this->getPlatform()->getMainUrl(), '/' ) . '/</span>
    <input class="' . DRTS_BS_PREFIX . 'form-control" name="permalink_slug_114" type="text" size="30" value="' . $this->H( $context->bundle->info['permalink_slug_114'] ?? ( $context->bundle->group . '-' . $context->bundle->info['slug'] ) ) . '" />
    <span class="' . DRTS_BS_PREFIX . 'text-nowrap ' . DRTS_BS_PREFIX . 'mx-1">/</span>
    <select class="' . DRTS_BS_PREFIX . 'form-select" name="permalink_path_114">' . implode( PHP_EOL, $this->_pathsToOptions( $context->bundle, $paths ) ) . '</select></div>',
						'#horizontal' => true,
						'#weight'     => 3,
						'#states'     => array(
							'visible' => array(
								'[name="permalink_type"]' => array( 'value' => '114compat' ),
							),
						),
					);
				}
			} else {
				$form['seo']['single']['slug'] = array(
					'#type'                => 'textfield',
					'#title'               => __( 'Default slug', 'directories-pro' ),
					'#default_value'       => $context->bundle->info['slug'],
					'#horizontal'          => true,
					'#placeholder'         => $info['slug'],
					'#required'            => true,
					'#regex'               => '/^[a-z0-9-_]+$/',
					'#max_length'          => 30,
					'#regex_error_message' => __( 'Only alphanumeric characters, underscores, and dashes are allowed.', 'directories-pro' ),
				);
			}
		}

		if ( empty( $info['is_taxonomy'] )
			&& empty( $info['is_user'] )
			&& empty( $info['no_title'] )
		) {
			$title_fields = $this->Entity_Field_options(
				$context->bundle,
				array(
					'interface'       => 'Field\Type\ITitle',
					'return_disabled' => true,
					'type_exclude'    => 'entity_title',
				)
			);
			if ( ! empty( $title_fields[0] ) ) {
				$form['general']['title']                = array(
					'#title'  => __( 'Title Settings', 'directories-pro' ),
					'#weight' => 30,
					'#tree'   => false,
				);
				$form['general']['title']['no_title']    = array(
					'#type'          => 'checkbox',
					'#title'         => __( 'Disable default title field', 'directories-pro' ),
					'#default_value' => ! empty( $context->bundle->info['no_title'] ),
					'#horizontal'    => true,
				);
				$form['general']['title']['title_field'] = array(
					'#type'             => 'select',
					'#title'            => __( 'Autofill title from another field', 'directories-pro' ),
					'#options'          => $title_fields[0],
					'#options_disabled' => array_keys( $title_fields[1] ),
					'#default_value'    => ! empty( $context->bundle->info['title_field'] ) ? $context->bundle->info['title_field'] : ( isset( $title_fields[0]['post_content'] ) ? 'post_content' : null ),
					'#horizontal'       => true,
					'#states'           => array(
						'visible' => array(
							'[name="no_title"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				);
			}
		}

		if ( isset( $info['entity_image'] )
			|| isset( $info['entity_icon'] )
		) {
			$form['general']['image'] = array(
				'#title'  => __( 'Image Settings', 'directories-pro' ),
				'#weight' => 40,
				'#tree'   => false,
			);
			if ( isset( $info['entity_image'] ) ) {
				$image_fields                             = $this->Entity_Field_options(
					$context->bundle,
					array(
						'interface'       => 'Field\Type\IImage',
						'return_disabled' => true,
					)
				);
				$form['general']['image']['entity_image'] = array(
					'#type'             => 'select',
					'#title'            => __( 'Default image field', 'directories-pro' ),
					'#options'          => array( '' => '— ' . __( 'Select field', 'directories-pro' ) . ' —' ) + $image_fields[0],
					'#options_disabled' => array_keys( $image_fields[1] ),
					'#default_value'    => ! empty( $context->bundle->info['entity_image'] ) ? $context->bundle->info['entity_image'] : null,
					'#horizontal'       => true,
				);
			}
			if ( isset( $info['entity_icon'] ) ) {
				$icon_fields = $this->Entity_Field_options(
					$context->bundle,
					array(
						'interface'       => 'Field\Type\IconType',
						'return_disabled' => true,
					)
				);
				if ( ! isset( $image_fields ) ) {
					$image_fields = $this->Entity_Field_options(
						$context->bundle,
						array(
							'interface'       => 'Field\Type\IImage',
							'return_disabled' => true,
						)
					);
				}
				$form['general']['image']['entity_icon']  = array(
					'#type'             => 'select',
					'#title'            => __( 'Default icon field', 'directories-pro' ),
					'#options'          => array( '' => '— ' . __( 'Select field', 'directories-pro' ) . ' —' ) + $icon_fields[0] + $image_fields[0],
					'#options_disabled' => array_keys( $icon_fields[1] + $image_fields[1] ),
					'#default_value'    => ! empty( $context->bundle->info['entity_icon'] ) ? $context->bundle->info['entity_icon'] : null,
					'#horizontal'       => true,
				);
				$color_fields                             = $this->Entity_Field_options(
					$context->bundle,
					array(
						'interface'       => 'Field\Type\ColorType',
						'return_disabled' => true,
					)
				);
				$form['general']['image']['entity_color'] = array(
					'#type'             => 'select',
					'#title'            => __( 'Default color field', 'directories-pro' ),
					'#options'          => array( '' => '— ' . __( 'Select field', 'directories-pro' ) . ' —' ) + $color_fields[0],
					'#options_disabled' => array_keys( $color_fields[1] ),
					'#default_value'    => ! empty( $context->bundle->info['entity_color'] ) ? $context->bundle->info['entity_color'] : null,
					'#horizontal'       => true,
				);
			}
		}

		if ( ! empty( $info['is_taxonomy'] ) ) {
			$sort_fields             = $this->Entity_Field_options(
				$context->bundle,
				array(
					'type'            => array( 'entity_id', 'entity_title', 'entity_term_content_count', 'choice', 'boolean', 'number', 'string' ),
					'return_disabled' => true,
					'name_property'   => true,
				)
			);
			$form['general']['sort'] = array(
				'#title'     => __( 'Sort Settings', 'directories-pro' ),
				'#weight'    => 42,
				'#tree'      => false,
				'sort_field' => array(
					'#title'            => __( 'Default sort field', 'directories-pro' ),
					'#type'             => 'select',
					'#options'          => $sort_fields[0],
					'#options_disabled' => array_keys( $sort_fields[1] ),
					'#default_value'    => isset( $context->bundle->info['sort_field'] ) ? $context->bundle->info['sort_field'] : 'title',
					'#horizontal'       => true,
				),
				'sort_order' => array(
					'#title'         => __( 'Sort direction', 'directories-pro' ),
					'#type'          => 'select',
					'#options'       => array(
						'ASC'  => __( 'Ascending (ASC)', 'directories-pro' ),
						'DESC' => __( 'Descending (DESC)', 'directories-pro' ),
					),
					'#horizontal'    => true,
					'#default_value' => isset( $context->bundle->info['sort_order'] ) && $context->bundle->info['sort_order'] === 'DESC' ? 'DESC' : 'ASC',
				),
			);
		}

		if ( ! empty( $info['expirable'] ) ) {
			$form['general']['expiry']                         = array(
				'#title'        => __( 'Expiry Settings', 'directories-pro' ),
				'#weight'       => 45,
				'#tree'         => false,
				'entity_expire' => array(
					'#title'         => __( 'Enable expiration date', 'directories-pro' ),
					'#type'          => 'checkbox',
					'#horizontal'    => true,
					'#default_value' => ! empty( $context->bundle->info['entity_expire'] ),
				),
			);
			$form['general']['expiry']['entity_expire_status'] = array(
				'#title'         => __( 'Status after expiration', 'directories-pro' ),
				'#type'          => 'select',
				'#options'       => array(
					'trash' => __( 'Trash', 'directories-pro' ),
					'draft' => __( 'Draft', 'directories-pro' ),
				),
				'#horizontal'    => true,
				'#default_value' => ! empty( $context->bundle->info['entity_expire_status'] ) ? $context->bundle->info['entity_expire_status'] : null,
				'#states'        => array(
					'visible' => array(
						'[name="entity_expire"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			);
			$date_fields                                       = $this->_application->Entity_Field_options(
				$context->bundle->name,
				array(
					'type'              => 'date',
					'exclude'           => array( 'entity_expires' ),
					'empty_value'       => '',
					'empty_value_label' => __( 'Default', 'directories-pro' ),
					'return_disabled'   => true,
				)
			);
			if ( ! empty( $date_fields[0] )
				|| ! empty( $date_fields[1] )
			) {
				$form['general']['expiry']['entity_expire_field'] = array(
					'#title'            => __( 'Expiration date field', 'directories-pro' ),
					'#type'             => 'select',
					'#options'          => $date_fields[0],
					'#options_disabled' => array_keys( $date_fields[1] ),
					'#horizontal'       => true,
					'#default_value'    => ! empty( $context->bundle->info['entity_expire_field'] ) ? $context->bundle->info['entity_expire_field'] : '',
					'#states'           => array(
						'visible' => array(
							'[name="entity_expire"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				);
			}
			$form['general']['expiry']['entity_expire_days'] = array(
				'#title'         => __( 'Default expiration period', 'directories-pro' ),
				'#description'   => sprintf( __( 'This setting applies to %s submitted from the frontend only.', 'directories-pro' ), strtolower( $context->bundle->getLabel() ) ),
				'#type'          => 'slider',
				'#min_text'      => __( 'Unlimited', 'directories-pro' ),
				'#field_suffix'  => __( 'day(s)', 'directories-pro' ),
				'#min_value'     => 0,
				'#max_value'     => 365,
				'#integer'       => true,
				'#horizontal'    => true,
				'#default_value' => ! empty( $context->bundle->info['entity_expire_days'] ) ? $context->bundle->info['entity_expire_days'] : 0,
				'#states'        => array(
					'visible' => array(
						'[name="entity_expire"]' => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
			);

			$ref_bundles      = $ref_bundle_descriptions = array();
			$reference_fields = $this->_application->Entity_Field_options(
				$context->bundle->name,
				array(
					'type'            => 'entity_reference',
					'return_disabled' => true,
				)
			);
			foreach ( array_keys( $reference_fields[0] + $reference_fields[1] ) as $reference_field_name ) {
				if ( $reference_field = $this->_application->Entity_Field( $context->bundle, $reference_field_name ) ) {
					$reference_field_settings = $reference_field->getFieldSettings();
					if ( ! empty( $reference_field_settings['bundle'] )
						&& ( $reference_bundle = $this->_application->Entity_Bundle( $reference_field_settings['bundle'] ) )
					) {
						$key                             = $reference_field_name;
						$ref_bundles[ $key ]             = $reference_bundle->getGroupLabel() . ' - ' . $reference_bundle->getLabel() . ' ';
						$ref_bundle_descriptions[ $key ] = sprintf( __( 'Referencing using the field "%1$s" (%2$s).', 'directories-pro' ), $reference_field->getFieldLabel(), $reference_field_name );
					}
				}
			}
			foreach ( $this->_application->Entity_Bundles_referencing( $context->bundle->name ) as $reference_field_name => $reference_bundle_names ) {
				foreach ( $reference_bundle_names as $reference_bundle_name ) {
					if ( ( $reference_bundle = $this->_application->Entity_Bundle( $reference_bundle_name ) )
						&& ( $reference_field = $this->_application->Entity_Field( $reference_bundle_name, $reference_field_name ) )
					) {
						$key                             = $reference_bundle_name . ',' . $reference_field_name;
						$ref_bundles[ $key ]             = $reference_bundle->getGroupLabel() . ' - ' . $reference_bundle->getLabel();
						$ref_bundle_descriptions[ $key ] = sprintf( __( 'Referenced using the field "%1$s" (%2$s).', 'directories-pro' ), $reference_field->getFieldLabel(), $reference_field_name );
					}
				}
			}
			if ( ! empty( $ref_bundles ) ) {
				$form['general']['expiry']['entity_expire_ref']         = array(
					'#title'         => __( 'Expire referencing/referenced items', 'directories-pro' ),
					'#type'          => 'checkbox',
					'#horizontal'    => true,
					'#default_value' => ! empty( $context->bundle->info['entity_expire_ref'] ),
					'#states'        => array(
						'visible' => array(
							'[name="entity_expire"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				);
				$form['general']['expiry']['entity_expire_ref_bundles'] = array(
					'#type'                => 'checkboxes',
					'#options'             => $ref_bundles,
					'#options_description' => $ref_bundle_descriptions,
					'#horizontal'          => true,
					'#default_value'       => ! empty( $context->bundle->info['entity_expire_ref_bundles'] ) ? $context->bundle->info['entity_expire_ref_bundles'] : null,
					'#states'              => array(
						'visible' => array(
							'[name="entity_expire"]'     => array(
								'type'  => 'checked',
								'value' => true,
							),
							'[name="entity_expire_ref"]' => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
				);
			}
		}

		if ( ! empty( $info['levelable'] ) ) {
			// Levels
			$form['general']['levels'] = array(
				'#title'       => __( 'Feature Level Settings', 'directories-pro' ),
				'#weight'      => 50,
				'#tree'        => false,
				'entity_level' => $this->_application->Entity_Levels_settingsForm( $context->bundle ),
			);
		}

		if ( empty( $info['is_taxonomy'] )
			&& ! empty( $info['public'] )
		) {
			$form['seo']['entity_schemaorg'] = array(
				'#tree'   => true,
				'#title'  => __( 'Schema.org Settings', 'directories-pro' ),
				'#weight' => 50,
			) + $this->Entity_SchemaOrg_settingsForm(
				$context->bundle,
				empty( $context->bundle->info['entity_schemaorg'] ) ? array() : $context->bundle->info['entity_schemaorg'],
				array( 'entity_schemaorg' )
			);
			$form['seo']['entity_opengraph'] = array(
				'#tree'   => true,
				'#title'  => __( 'Open Graph Settings', 'directories-pro' ),
				'#weight' => 60,
			) + $this->Entity_OpenGraph_settingsForm(
				$context->bundle,
				empty( $context->bundle->info['entity_opengraph'] ) ? array() : $context->bundle->info['entity_opengraph'],
				array( 'entity_opengraph' )
			);
		}

		$submitted_values = $this->_getSubimttedValues( $context, $formStorage );

		// Add bundle type specific settings
		$form['general'][ $context->bundle->type ]  = array(
			'#tree'   => false,
			'#weight' => 99,
		);
		$form['general'][ $context->bundle->type ] += (array) $this->Entity_BundleTypes_impl( $context->bundle->type )
			->entityBundleTypeSettingsForm( $context->bundle->info, array(), $submitted_values );

		$form = $this->Filter( 'entity_admin_bundle_settings_form', $form, array( $context->bundle, $submitted_values ) );

		if ( isset( $form['seo'] ) ) {
			$form['#tabs']['seo'] = array(
				'#title' => __( 'SEO', 'directories-pro' ),
			);
			$form['seo']         += array(
				'#tab'    => 'seo',
				'#weight' => 60,
				'#tree'   => false,
			);
		}

		if ( count( $form['#tabs'] ) <= 1 ) {
			$form['#tabs'] = array();
		}

		return $form;
	}

	protected function _pathsToOptions( Bundle $bundle, array $paths ) {
		$options = array();
		foreach ( $this->Filter( 'entity_admin_bundle_permalink_paths', $paths, array( $bundle ) ) as $_path ) {
			$display_path = str_replace( '/', ' / ', trim( $_path, '/' ) );
			$selected     = isset( $bundle->info['permalink_path'] ) && $_path === $bundle->info['permalink_path'] ? ' selected="selected"' : '';
			$options[]    = '<option value="' . $_path . '"' . $selected . '>' . $this->H( $display_path ) . '</option>';
		}
		return $options;
	}

	protected function _getLabelSettingsForm( Bundle $bundle, array $info ) {
		$form   = array(
			'#title'         => __( 'Label Settings', 'directories-pro' ),
			'#weight'        => 1,
			'#tree'          => false,
			'label'          => array(
				'#type'          => 'textfield',
				'#title'         => __( 'Label', 'directories-pro' ),
				'#default_value' => $bundle->getLabel(),
				'#horizontal'    => true,
				'#placeholder'   => isset( $info['label'] ) ? $info['label'] : null,
				'#required'      => true,
				'#weight'        => -2,
			),
			'label_singular' => array(
				'#type'          => 'textfield',
				'#title'         => __( 'Singular label', 'directories-pro' ),
				'#default_value' => $bundle->getLabel( 'singular' ),
				'#horizontal'    => true,
				'#placeholder'   => isset( $info['label_singular'] ) ? $info['label_singular'] : null,
				'#required'      => true,
				'#weight'        => -1,
			),
		);
		$labels = array(
			'add'    => __( 'Add item label', 'directories-pro' ),
			'all'    => __( 'All items label', 'directories-pro' ),
			'select' => __( 'Select item label', 'directories-pro' ),
			'count'  => __( 'Item count label', 'directories-pro' ),
			'count2' => __( 'Item count label (plural)', 'directories-pro' ),
		);
		foreach ( $labels as $label_name => $label_title ) {
			$label_setting_name = 'label_' . $label_name;
			if ( isset( $info[ $label_setting_name ] ) ) {
				$form[ $label_setting_name ] = array(
					'#type'          => 'textfield',
					'#title'         => $label_title,
					'#default_value' => $bundle->getLabel( $label_name ),
					'#horizontal'    => true,
					'#placeholder'   => is_string( $info[ $label_setting_name ] ) ? $info[ $label_setting_name ] : null,
					'#required'      => true,
				);
			}
		}
		if ( ! empty( $info['public'] ) ) {
			if ( ! empty( $info['is_taxonomy'] )
				|| ! empty( $info['is_user'] )
				|| ! empty( $info['parent'] )
				|| ! empty( $info['parent_field'] )
			) {
				$form['label_page'] = array(
					'#type'          => 'textfield',
					'#title'         => __( 'Single item page label', 'directories-pro' ),
					'#default_value' => $bundle->getLabel( 'page' ),
					'#horizontal'    => true,
					'#placeholder'   => is_string( $info['label_page'] ) ? $info['label_page'] : null,
					'#required'      => true,
				);
			}
		}

		if ( $bundle->entitytype_name === 'post' ) {
			$form['label_author'] = array(
				'#type'          => 'textfield',
				'#title'         => __( 'Author label', 'directories-pro' ),
				'#default_value' => ( $label = $bundle->getLabel( 'author' ) ) ? $label : __( 'Author', 'directories-pro' ),
				'#horizontal'    => true,
				'#placeholder'   => is_string( $info['label_author'] ) ? $info['label_author'] : __( 'Author', 'directories-pro' ),
				'#required'      => true,
			);
		}

		return $form;
	}

	protected function _saveConfig( Context $context, array $values, Form\Form $form ) {
		parent::_saveConfig( $context, $values, $form );

		$this->Action( 'entity_admin_bundle_settings_save', array( $context->bundle, &$values ) );

		// Save icon
		if ( $this->Entity_BundleTypeInfo( $context->bundle, 'entity_icon' ) !== null ) {
			if ( ! empty( $values['entity_icon'] )
				&& ( $icon_field = $this->_application->Entity_Field( $context->bundle, $values['entity_icon'] ) )
			) {
				$values['entity_icon_is_image'] = $icon_field->getFieldType() !== 'icon';
			} else {
				$values['entity_icon'] = null;
			}
		}

		// Clear taxonomy cache if image/icon/sort settings changed
		if ( ! empty( $context->bundle->info['is_taxonomy'] ) ) {
			if ( ( isset( $values['entity_image'] ) && $context->bundle->info['entity_image'] !== $values['entity_image'] )
				|| ( isset( $values['entity_icon'] ) && $context->bundle->info['entity_icon'] !== $values['entity_icon'] )
				|| ( isset( $values['sort_field'] ) && $context->bundle->info['sort_field'] !== $values['sort_field'] )
				|| ( isset( $values['sort_order'] ) && $context->bundle->info['sort_order'] !== $values['sort_order'] )
			) {
				$clear_taxonomy_cache = true;
			}
		}

		if ( ! empty( $context->bundle->info['is_primary'] )
			&& $context->bundle->entitytype_name === 'post'
		) {
			if ( isset( $values['permalink_type'] ) ) {
				if ( $values['permalink_type'] === 'flat' ) {
					if ( ! empty( $values['permalink_flat_path'] ) ) {
						$values['permalink_path'] = $values['permalink_flat_path'];
					}
				} elseif ( $values['permalink_type'] === '114compat' ) {
					if ( ! empty( $values['permalink_path_114'] ) ) {
						$values['permalink_path'] = $values['permalink_path_114'];
					}
				}
			}
		}

		$old_info = $context->bundle->info;
		$context->bundle->setInfo( $values )->commit();

		if ( ! empty( $clear_taxonomy_cache ) ) {
			$this->Entity_TaxonomyTerms_clearCache( $context->bundle->name );
		}

		$this->Entity_Field_cleanCache( $context->bundle->name );

		$this->Action( 'entity_admin_bundle_settings_saved', array( $context->bundle, $old_info ) );
	}

	public function _validate( Form\Form $form, $bundle ) {
		if ( ! isset( $bundle->info['slug'] )
			|| empty( $bundle->info['public'] )
		) {
			return;
		}

		$slug = strtolower( trim( $form->values['slug'], " \t\n\r\0\x0B/" ) );
		if ( ! strlen( $slug ) ) {
			$form->setError( __( 'Permalink URL base may not be empty', 'directories-pro' ), 'permalink' );
			return;
		}
		if ( ! preg_match( '#^[a-z0-9_-]+$#', $slug ) ) {
			$form->setError( sprintf( __( 'Invalid permalink URL base: %s', 'directories-pro' ), $slug ), 'permalink' );
			return;
		}

		foreach ( $this->Entity_Bundles( null, $bundle->group ) as $_bundle ) {
			if ( ( $_bundle->name === $bundle->name )
				|| empty( $bundle->info['public'] )
			) {
				continue;
			}

			if ( $_bundle->info['slug'] === $slug ) {
				$form->setError(
					sprintf(
						__( 'Permalink URL base %1$s is already in use by %2$s.', 'directories-pro' ),
						'<em>' . $slug . '</em>',
						$_bundle->getLabel( 'singular' )
					),
					'permalink'
				);
				break;
			}
		}
	}
}
