<?php namespace BulkPriceEditor\ProductFilters;

use BulkPriceEditor\ProductFilters\Filters\ExcludedProducts;
use BulkPriceEditor\ProductFilters\Filters\Filter;
use BulkPriceEditor\ProductFilters\Filters\FilterByAttributes;
use BulkPriceEditor\ProductFilters\Filters\IncludedProducts;
use BulkPriceEditor\ProductFilters\Filters\ProductType;
use BulkPriceEditor\ProductFilters\Filters\StockStatus;
use BulkPriceEditor\ProductFilters\Filters\SKUAndName;
use BulkPriceEditor\ProductFilters\Templates\Template;
use BulkPriceEditor\ProductQuery\ProductQuery;

class FilterManager {
	
	protected array $rawFiltersData;
	
	protected array $filters = array();
	protected ?Template $template;
	
	public function __construct( array $rawFiltersData = array(), ?Template $template = null ) {
		$this->rawFiltersData = $rawFiltersData;
		$this->template       = $template;
		
		$this->initFilters();
	}
	
	protected function initFilters() {
		$this->filters = apply_filters( 'bulk_price_editor/query/filters', array(
			IncludedProducts::class,
			ExcludedProducts::class,
			StockStatus::class,
			ProductType::class,
			SKUAndName::class,
			FilterByAttributes::class,
		) );
		
		add_filter( 'posts_where', function ( $where, $query ) {
			global $wpdb;
			
			if ( isset( $query->query['bpe_title_filter'] ) ) {
				$prefix = $query->query['bpe_title_filter'];
				
				$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_title LIKE %s", '%' . $prefix . '%' );
			}
			
			return $where;
		}, 10, 2 );
	}
	
	/**
	 * Get the filters
	 *
	 * @return Filter[]
	 */
	public function getFilters(): array {
		return $this->filters;
	}
	
	public function filterQuery( ProductQuery $query ): ProductQuery {
		
		foreach ( $this->getFilters() as $filter ) {
			
			$filter = new $filter( $this->rawFiltersData, $this->template );
			
			$filter->filterQuery( $query );
		}
		
		return $query;
	}
}
