<?php
/**
 * @ViewsFilter("basket_get_price_field")
 */

namespace Drupal\basket\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\basket\Query\BasketGetNodePriceQuery;

class BasketGetPriceField extends FilterPluginBase{

    protected $basket;

    public function __construct(){
        call_user_func_array(array('parent', '__construct'), func_get_args());
        $this->basket = \Drupal::service('Basket');
    }

	protected function defineOptions(){
		$options = parent::defineOptions();
		$options['labelMIN'] = ['default' => 'Price from'];
		$options['labelMAX'] = ['default' => 'Price to'];
		return $options;
	}
	public function buildExposeForm(&$form, FormStateInterface $form_state){
		$form['expose']['labelMIN'] = [
			'#type'			=> 'textfield',
			'#title'		=> 'Label MIN',
			'#default_value'=> $this->options['labelMIN'],
		];
		$form['expose']['labelMAX'] = [
			'#type'			=> 'textfield',
			'#title'		=> 'Label MAX',
			'#default_value'=> $this->options['labelMAX'],
		];
		parent::buildExposeForm($form, $form_state);
	}

    public function buildExposedForm(&$form, FormStateInterface $form_state){
    	if (empty($this->options['exposed'])) {
      		return;
    	}
    	$identifier = $this->options['expose']['identifier'];
    	$form[$identifier] = [
    		'#type'			=> 'item',
    		'#wrapper_attributes'=> ['class' => ['items_combine']],
    		[
    			'min'			=> [
    				'#type'			=> 'number',
    				'#step'			=> 1,
    				'#title'        => !empty($this->options['labelMIN']) ? $this->basket->Translate()->t(trim($this->options['labelMIN'])) : '',
    				'#min'			=> 0,
    				'#parents'		=> [$identifier, 'min']
    			],
    			'arrow'			=> [
    				'#markup'		=> '<div class="arrow form-item"></div>'
    			],
    			'max'			=> [
    				'#type'			=> 'number',
    				'#step'			=> 1,
    				'#title'        => !empty($this->options['labelMAX']) ? $this->basket->Translate()->t(trim($this->options['labelMAX'])) : '',
    				'#min'			=> 0,
    				'#parents'		=> [$identifier, 'max']
    			]
    		]
    	];
    }
    public function acceptExposedInput($input){
    	if(!empty($input[$this->options['expose']['identifier']])){
    		$this->value = $input[$this->options['expose']['identifier']];
    		return TRUE;
    	}
    	return FALSE;
    }
	public function query(){
		if(!empty($this->value)){
			BasketGetNodePriceQuery::viewsJoin($this, 'MIN', $this->value);
		}
	}
}