<?php

/**
 * Snippet to run searches and show their results.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\search
 * @copyright Copyright (c) 2012 - 2014 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/* @var $tplEngine cfTemplateEngine */
$controller = $tplEngine->controller;

// Get and verify URL parameters
$q = flTextStrip::tags(clearFusionCMS::getRequest()->getQuery('q', ''));
$page = clearFusionCMS::getRequest()->getQuery('page', '0');
$page = preg_match('/^\d+$/', $page) ? $page : '0';

if(!empty($q)) {

	// Deal with parameters
	$class = isset($class) ? $class : 'searchResultsList';
	$words = isset($words) ? $words : 30;
	$perPage = isset($perPage) ? $perPage : 10;
	$searchIn = isset($searchIn) ? $searchIn : '';
	$matchAll = isset($matchAll) ? $matchAll : false;
	$fields = isset($fields) ? explode(',', $fields) : array();
	$summary = isset($summary) ? $summary : null;
	$resultTpl = isset($resultTpl) ? $tplEngine->getChunk($resultTpl) : '<li><a href="[[+link]]">[[+title]]</a><p>[[+summary]]</p></li>';
	$wrapperTpl = isset($wrapperTpl) ? $tplEngine->getChunk($wrapperTpl) : '<ul class="[[+class]]">[[+results]]</ul>';
	$containerTpl = isset($containerTpl) ? $tplEngine->getChunk($containerTpl) : '<p>' . __('[[+numResults]] results found for "[[+term]]"', 'search') . '</p>[[+results]][[+pagination]]';

	$params = array('q' => $q);

	// Run for advanced searches
	if(clearFusionCMS::getRequest()->hasParam('searchpath')) {
		$searchIn = clearFusionCMS::getRequest()->getParam('searchpath');
		$params['searchpath'] = $searchIn;
	}

	if(clearFusionCMS::getRequest()->hasParam('searchfields')) {
		$fields = clearFusionCMS::getRequest()->getParam('searchfields');
		$params['searchfields'] = $fields;
	}

	if(clearFusionCMS::getRequest()->hasParam('searchmatchall')) {
		$matchAll = clearFusionCMS::getRequest()->getParam('searchmatchall');
		$params['searchmatchall'] = $matchAll;
	}

	// Run the search
	$search = new flSearch(clearFusionCMS::getDb(), 'cf_search_' . clearFusionCMS::getSite());
	$results = $search->find(
		$q,
		$searchIn,
		true,
		true,
		clearFusionCMS::getUser()->getPermissions(),
		$fields,
		$page * $perPage,
		$perPage,
		$matchAll
	);

	// Build the search results
	$html = '';
	if(count($results)) {
		foreach($results as $result) {
			if(($helper = cfSearchHelper::getHelper($result['root'])) && ($sum = $helper->getSearchSummary($result['node'], $summary, $words))) {
				if(!isset($sum['link']))
					$sum['link'] = $sum['uri'];
				if(!isset($sum['img']))
					$sum['img'] = isset($sum['img']) ? $sum['img'] : '';

				$html .= $tplEngine->parseString($resultTpl, $sum);
			}
		}

		$html = $tplEngine->parseString($wrapperTpl, array('results' => $html, 'class' => $class));
	}

	$pagination = new flWidgetPagination($page, $results->total(), $perPage);
	$pagination->setURI($controller->content->getPageURI($controller->pageData['id']), $params, 'page');

	// Term without ranges and paths
	$qClean = preg_replace('/\bpath:"[^"]+"/i', '', $q);
	$qClean = preg_replace('/\bsort:"([a-z0-9_\.-]+):(asc|desc)"/i', '', $q);
	$qClean = preg_replace('/\b(([a-z0-9_\.-]+):\[\s*(-?[\d\.]+)?\s*(to|is)\s*(-?[\d\.]+)?\])/i', '', $qClean);
	$qClean = trim(preg_replace('/\s+/', ' ', $qClean));

	// Output the search results
	echo $tplEngine->parseString($containerTpl, array(
		'numResults' => (int)$results->total(),
		'term' => fusionLib::htmlChars($qClean),
		'termFull' => fusionLib::htmlChars($q),
		'results' => $html,
		'pagination' => $pagination->render()
	));
}
