<?php
namespace SabaiApps\Directories\Component\DirectoryPro\SystemWidget;

use SabaiApps\Directories\Component\System\Widget\AbstractWidget;

class FiltersSystemWidget extends AbstractWidget {

	protected $_cacheable = false;

	protected function _systemWidgetInfo() {
		return array(
			'title'   => __( 'Filter Form', 'directories-pro' ),
			'summary' => __( 'Displays a filter form.', 'directories-pro' ),
		);
	}

	protected function _getWidgetSettings( array $settings ) {
		$directory_options = array();
		foreach ( $this->_application->getModel( 'Directory', 'Directory' )->fetch() as $directory ) {
			if ( ! $this->_application->Directory_Types_impl( $directory->type, true ) ) {
				continue; // make sure the directory type is active
			}

			$directory_options[ $directory->name ] = $directory->getLabel();
		}
		if ( empty( $directory_options ) ) {
			return;
		}

		$directory_option_keys = array_keys( $directory_options );
		return array(
			'directory'      => array(
				'#title'         => __( 'Select directory', 'directories-pro' ),
				'#options'       => $directory_options,
				'#type'          => count( $directory_options ) <= 1 ? 'hidden' : 'select',
				'#default_value' => array_shift( $directory_option_keys ),
				'#multiple'      => true,
			),
			'hide_on_mobile' => array(
				'#title'         => __( 'Hide on mobile', 'directories-pro' ),
				'#type'          => 'checkbox',
				'#default_value' => false,
			),
		);
	}

	protected function _getWidgetContent( array $settings ) {
		if ( empty( $settings['directory'] )
			|| ( ! empty( $settings['hide_on_mobile'] ) && $this->_application->isMobile() )
		) {
			return;
		}

		$ret         = array();
		$directories = is_array( $settings['directory'] ) ? $settings['directory'] : array( $settings['directory'] );
		foreach ( $directories as $directory_name ) {
			if ( ! $bundle = $this->_application->Entity_Bundle( 'directory__listing', $directory_name ) ) {
				continue;
			}
			$ret[] = '<div class="drts-view-entities-filter-form-placeholder" data-bundle-group="' . $bundle->group . '" data-bundle-type="' . $bundle->type . '" style="display:none;"></div>';
		}

		return implode( PHP_EOL, $ret );
	}
}
