<?php
namespace SabaiApps\Directories\Component\View\FieldFilter;

use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Component\Field\IField;

class TermListFieldFilter extends AbstractTermFieldFilter {

	protected function _fieldFilterInfo() {
		$info                      = parent::_fieldFilterInfo();
		$info['label']             = __( 'Checkboxes', 'directories-pro' );
		$info['default_settings'] += array(
			'icon'          => true,
			'icon_size'     => 'sm',
			'andor'         => 'OR',
			'columns'       => 1,
			'visible_count' => 15,
			'scroll'        => true,
		);
		return $info;
	}

	public function fieldFilterSettingsForm( IField $field, array $settings, array $parents = array() ) {
		$ret = parent::fieldFilterSettingsForm( $field, $settings, $parents );

		if ( ! is_array( $ret ) ) {
			return;
		}

		$taxonomy_bundle = $field->getTaxonomyBundle();
		if ( $this->_application->Entity_BundleTypeInfo( $taxonomy_bundle, 'entity_image' )
			|| $this->_application->Entity_BundleTypeInfo( $taxonomy_bundle, 'entity_icon' )
		) {
			$ret += array(
				'icon'      => array(
					'#type'          => 'checkbox',
					'#title'         => __( 'Show icon', 'directories-pro' ),
					'#default_value' => ! empty( $settings['icon'] ),
					'#weight'        => 6,
				),
				'icon_size' => array(
					'#type'          => 'select',
					'#title'         => __( 'Icon size', 'directories-pro' ),
					'#options'       => $this->_application->System_Icon_sizeOptions(),
					'#default_value' => $settings['icon_size'],
					'#states'        => array(
						'visible' => array(
							sprintf( 'input[name="%s[icon]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array(
								'type'  => 'checked',
								'value' => true,
							),
						),
					),
					'#weight'        => 6,
				),
			);
		}

		$ret += array(
			'andor'         => array(
				'#title'         => __( 'Match type', 'directories-pro' ),
				'#type'          => 'select',
				'#options'       => array(
					'OR'  => __( 'Match any', 'directories-pro' ),
					'AND' => __( 'Match all', 'directories-pro' ),
					'NOT' => __( 'Match none', 'directories-pro' ),
				),
				'#default_value' => $settings['andor'],
				'#states'        => array(
					'visible' => array(
						sprintf( '[name="%s[type]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array( 'value' => 'checkboxes' ),
					),
				),
				'#weight'        => 20,
			),
			'visible_count' => array(
				'#type'          => 'slider',
				'#integer'       => true,
				'#min_value'     => 0,
				'#max_value'     => 50,
				'#min_text'      => __( 'Show all', 'directories-pro' ),
				'#title'         => __( 'Number of options to display', 'directories-pro' ),
				'#description'   => __( 'If there are more options than the number specified, those options are hidden until "more" link is clicked.', 'directories-pro' ),
				'#default_value' => $settings['visible_count'],
				'#weight'        => 30,
				'#states'        => array(
					'visible' => array(
						sprintf( '[name="%s[columns]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array( 'value' => 1 ),
					),
				),
			),
			'columns'       => array(
				'#type'          => 'select',
				'#title'         => __( 'Number of columns', 'directories-pro' ),
				'#options'       => array(
					1 => 1,
					2 => 2,
					3 => 3,
					4 => 4,
				),
				'#default_value' => $settings['columns'],
				'#weight'        => 29,
			),
			'scroll'        => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Show scroll bar', 'directories-pro' ),
				'#weight'        => 31,
				'#default_value' => ! empty( $settings['scroll'] ),
				'#states'        => array(
					'visible' => array(
						sprintf( '[name="%s[visible_count]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array( 'value' => 0 ),
						sprintf( '[name="%s[columns]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array( 'value' => 1 ),
					),
				),
			),
		);

		return $ret;
	}

	public function fieldFilterForm( IField $field, $filterName, array $settings, $request = null, ?Entity\Type\Query $query = null, ?array $current = null, $autoSubmit = true, $enableFacetCount = false, array $parents = array() ) {
		// Get taxonomy bundle associated with the field
		if ( ! $bundle = $field->getTaxonomyBundle() ) {
			return;
		}

		$queried_terms = $this->_getQueriedTerms( $field, $bundle, $query, $request );

		if ( false === $facets = $this->_getFacets( $field, $settings, $query, $enableFacetCount ) ) {
			return;
		}

		if ( ! isset( $current ) ) {
			$options = array(
				'content_bundle' => $field->Bundle->name,
				'hide_empty'     => ! empty( $settings['hide_empty'] ),
				'hide_count'     => ! $enableFacetCount || ! empty( $settings['hide_count'] ),
				'link'           => false,
				'icon'           => ! empty( $settings['icon'] ),
				'icon_size'      => $settings['icon_size'],
				'return_array'   => true,
				'prefix'         => '',
				'exclude'        => $this->_getExcludedTerms( $field, $settings ),
			);
			if ( empty( $bundle->info['is_hierarchical'] ) ) {
				$options += array(
					'limit' => $settings['num'],
					'depth' => 1,
				);
			} else {
				// Hierarchical taxonomy
				$options += array(
					'depth'  => $settings['depth'],
					'parent' => ! empty( $queried_terms ) && count( $queried_terms ) === 1 ? current( array_keys( $queried_terms ) ) : 0,
				);
			}
			if ( ! $list = $this->_application->Entity_TaxonomyTerms_html( $bundle->name, $options ) ) {
				if ( empty( $queried_terms ) ) {
					return;
				}

				// Render current term IDs as hidden values for conditional rules to work properly
				return $this->_getTermsHiddenField( $queried_terms );
			}

			$current = array(
				'#type'                    => 'checkboxes',
				'#disable_select_all'      => true,
				'#options'                 => $list,
				'#option_no_escape'        => true,
				'#options_visible_count'   => $settings['visible_count'],
				'#options_scroll'          => ! empty( $settings['scroll'] ),
				'#entity_filter_form_type' => 'checkboxes',
				'#columns'                 => ! $this->_application->isRunning() || empty( $settings['columns'] ) ? 1 : $settings['columns'],
				'#skip_invalid_option'     => true,
			);
			if ( ! empty( $queried_terms ) ) {
				// render current term IDs as hidden values for conditional rules to work properly
				foreach ( $queried_terms as $queried_term_id => $queried_term_slug ) {
					$current['#attributes'][ $queried_term_id ]['data-alt-value'] = $queried_term_slug;
					$current['#options_disabled'][]                               = $current['#options_hidden'][] = $queried_term_id;
				}
			}
		}

		if ( $current['#type'] === 'hidden' ) {
			return $current;
		}

		if ( isset( $facets ) ) {
			$this->_loadFacetCounts( $current, $facets, $settings, $request );
		}

		return empty( $current['#options'] ) ? null : $current;
	}

	public function fieldFilterLabels( IField $field, array $settings, $value, $form, $defaultLabel ) {
		// Get taxonomy bundle associated with the field
		if ( ! $bundle = $field->getTaxonomyBundle() ) {
			return;
		}

		$ret = array();
		foreach ( $this->_application->Entity_Entities( $bundle->entitytype_name, (array) $value, false ) as $entity ) {
			$ret[ $entity->getId() ] = $this->_application->H( $entity->getTitle() );
		}

		return $ret;
	}

	protected function _getMatchType( IField $field, array $settings ) {
		return $settings['andor'];
	}
}
