<?php
class WoofilterProControllerWpf extends ControllerWpf {
	public function autocompliteSearchText() {
		$res = new ResponseWpf();
		$value = ReqWpf::getVar('value');

		$data = array();
		if (!is_null($value)) {
			$args = array(
				'post_status' => 'publish',
				'post_type' => 'product',
				'posts_per_page' => 100,
				'ignore_sticky_posts' => true
			);

			add_filter('posts_where', function( $where ) use( $value ) {
				global $wpdb;
				$term = '%' . $wpdb->esc_like($value) . '%';
				$where .= ' AND ' . $wpdb->prepare("($wpdb->posts.post_title LIKE %s)", $term);
				return $where;
			});
			$query = new WP_Query($args);
			
			$regex = '~(' . $value . '\w+)~i';
			foreach ($query->posts as $term) {
				if (!empty($term->post_title)) {
					$title = $term->post_title;
					if (preg_match_all($regex, $title, $matches, PREG_PATTERN_ORDER)) {
						foreach ($matches[1] as $word) {
							if (!in_array($word, $data)) {
								$data[] = $word;
							}
						}
						if (count($data) > 10) {
							break;
						}
					}
				}
			}
		}
		$res->addData('words', $data);
		return $res->ajaxExec();
	}

	public function applyLoader() {
		$res = new ResponseWpf();
		$id = ReqWpf::getVar('id');
		$settings = ReqWpf::getVar('settings');

		$model = FrameWpf::_()->getModule('woofilters')->getModel('woofilters');
		$filters = $model->getFromTbl();
		$cnt = 0;
		foreach ($filters as $filter) {
			$current = unserialize($filter['setting_data']);
			if ( $filter['id'] != $id && isset($current['settings']) ) {
				$filter['settings'] = array_merge($current['settings'], $settings);
				unset($filter['setting_data']);
				$model->save($filter);
				$cnt++;
			}
		}
		$res->addData('message', $cnt . esc_html__(' filters have been changed', 'woo-product-filter'));
		return $res->ajaxExec();
	}
}
