<?php
namespace SabaiApps\Directories\Component\Field\Filter;

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

class MonthFilter extends AbstractFilter {

	protected function _fieldFilterInfo() {
		return array(
			'label'            => __( 'Month picker', 'directories-pro' ),
			'field_types'      => array( 'date' ),
			'default_settings' => array(),
		);
	}

	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() ) {
		return array(
			'#type'         => 'monthpicker',
			'#disable_time' => true,
		);
	}

	public function fieldFilterIsFilterable( IField $field, array $settings, &$value, ?array $requests = null ) {
		return ! empty( $value );
	}

	public function fieldFilterDoFilter( Query $query, IField $field, array $settings, $value, array &$sorts ) {
		$from = ( new \DateTime( $value, new \DateTimeZone( 'UTC' ) ) )->getTimestamp();
		$to   = ( new \DateTime( $value, new \DateTimeZone( 'UTC' ) ) )
			->modify( 'last day of this month' )
			->setTime( 23, 59, 59 )
			->getTimestamp();
		$query->fieldIsOrGreaterThan( $field, $from )->fieldIsSmallerThan( $field, $to );
	}

	public function fieldFilterLabels( IField $field, array $settings, $value, $form, $defaultLabel ) {
		$format = $this->_application->getPlatform()->getDateFormat();
		$from   = ( new \DateTime( $value, new \DateTimeZone( 'UTC' ) ) )->getTimestamp();
		$to     = ( new \DateTime( $value, new \DateTimeZone( 'UTC' ) ) )
			->modify( 'last day of this month' )
			->setTime( 23, 59, 59 )
			->getTimestamp();
		return array( '' => $this->_application->H( $defaultLabel ) . ': ' . date( $format, $from ) . ' - ' . date( $format, $to ) );
	}
}
