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

use SabaiApps\Directories\Context;

class FilterEntities extends AbstractQueryEntities {

	protected function _doExecute( Context $context ) {
		// Clear settings so they are not cached to prevent trying to load a view
		$settings                   = $context->settings;
		$settings['filter']['show'] = $settings['filter_only'] = true;
		$context->settings          = $settings;

		parent::_doExecute( $context );

		if ( $context->isError() ) {
			return;
		}

		// Notify
		$this->Action( 'view_filter_entities', array( $context ) );

		// Set template
		if ( ! $context->hasTemplate() ) {
			$context->addTemplate( 'view_filter_entities' );
		}
		if ( $is_ajax = $context->getRequest()->isAjax() ) {
			$context->setContentType( 'json' );
		}

		$html_attributes = array(
			'style' => '',
			'class' => $this->_settings['class'] ?? '',
		);
		if ( isset( $this->_settings['style'] )
			&& strlen( $this->_settings['style'] ) > 0
		) {
			$html_attributes['style'] .= $this->_settings['style'];
		}
		$context->html_attributes = $html_attributes;
		$context->btn_size        = isset( $this->_settings['btn_size'] ) && in_array( $this->_settings['btn_size'], array( 'sm', 'lg' ) ) ? $this->_settings['btn_size'] : null;
		$context->btn_color       = $this->_settings['btn_color'] ?? 'primary';
		$context->bg_color        = $this->_settings['bg_color'] ?? null;
	}

	protected function _getFilterFormOptions( Context $context, array $urlParams = array(), array $options = array() ) {
		$view_path              = $context->bundle->getPath( false );
		$options                = parent::_getFilterFormOptions( $context, $urlParams, $options );
		$options['method']      = 'get';
		$options['target']      = '.drts-view-filter-entities';
		$options['auto_submit'] = true;
		$options['attributes']  = array(
			'data-view-filter-ajax-url'        => (string) $this->Url( $view_path . '/filter' ),
			'data-view-filter-ajax-no-loading' => 1,
			'data-scroll-offset'               => -1,
		);
		$options['push_state']  = false;
		if ( empty( $this->_settings['is_default_view'] )
			&& ( isset( $this->_settings['path'] ) )
		) {
			$view_path = '/' . ltrim( $this->_settings['path'], '/' );
		}
		$options['url'] = $this->Url( $view_path, $urlParams );
		return $options;
	}
}
