<?php

/**
 * Snippet to display the search form.
 *
 * 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 - 2013 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

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

// Passed parameters
$resultsPage = isset($resultsPage) ? $resultsPage : 0;
$adv = isset($adv) ? $adv : 0;
$searchIn = isset($searchIn) ? $searchIn : '=All';
$usePlaceholder = isset($labelAs) && $labelAs == 'placeholder' ? true : false;
$label = isset($label) ? $label : __('Search For', 'search');

$form = new flForm(clearFusionCMS::getRequest(), 'searchform', $controller->content->getPageURI($resultsPage), false);

if(isset($type) && $type == 'search')
	$query = new flFormElementSearch($form, 'q');
else
	$query = new flFormElementText($form, 'q');
if($usePlaceholder)
	$query->setPlaceholder($label)->setCSS('keepPlaceholder');
else
	$query->setLabel($label);

if($searchIn !== '=All') {
	$searchIn = explode(',', $searchIn);
	$searchInOpts = array();
	foreach($searchIn as $item) {
		list($k, $d) = explode('=', $item);
		$searchInOpts[trim($k)] = trim($d);
	}

	if(count($searchInOpts) > 1) {
		$inPath = new flFormElementSelect($form, 'searchpath', clearFusionCMS::getRequest()->getQuery('searchpath'), $searchInOpts);
		$inPath->setLabel(__('Search In', 'search'));
	}
}

// If using advanced search
if($adv) {
	$fields = unserialize(clearFusionCMS::getDb()->fetchOne('SELECT value FROM cf_search_' . clearFusionCMS::getSite() . '_config WHERE keyname=?', 'cfFieldDesc'));

	// If field names given limit advanced search to those
	if($adv !== '1') {
		$flds = array();
		$f = explode(',', $adv);
		foreach($f as $fn) {
			$fn = trim($fn);
			if(!empty($fn))
				$flds[] = $fn;
		}
		$fields = array_intersect_key($fields, array_flip($flds));
	}

	if(count($fields)) {
		$infields = new flFormElementChecklist($form, 'searchfields', clearFusionCMS::getRequest()->getQuery('searchfields', array()), $fields);
		$infields->setLabel(__('Limit Search To', 'search'));
	}

	$matchAll = new flFormElementCheckbox($form, 'searchmatchall', clearFusionCMS::getRequest()->getQuery('searchmatchall', false));
	$matchAll->setLabel(__('All Search Terms Must Be Present', 'search'));
}

$search = new flFormElementSubmit($form, 'dosearch');
$search->setCaption(__('Search', 'search'))->setCSS('primary');

echo $form->render($tplEngine->getCodeBuffer());
