<?php

/**
 * 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 fusionLib
 * @copyright Copyright (c) 2007 - 2016 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flFormElementSelect Class
 *
 * Select form element.
 *
 * @package fusionLib
 */
class flFormElementSelect extends flFormElement {

	/**
	 * Options
	 *
	 * @var array
	 */
	protected $options;

	/**
	 * The pattern to mark option groups.
	 *
	 * @var string
	 */
	protected $grpPattern = null;

	/**
	 *	Construct the element.
	 *
	 *	@param flForm $form The form the element will be used with.
	 *	@param string $name The name of the element.
	 *	@param string $default The default value of the element.
	 *	@param array $options The options for the select
	 */
	function __construct($form, $name, $default, $options) {
		parent::__construct($form, $name, $default);
		$this->options = $options;
	}

	/**
	 * Set the pattern used for marking option groups.
	 *
	 * @param string $pattern The regular expression.
	 * @return flFormElementSelect This object.
	 */
	function setGroupPattern($pattern = '/^--/') {
		$this->grpPattern = $pattern;
		return $this;
	}

	/**
	 * Process the request data, normally called by the flForm::isSubmitted().
	 * Validation of the data is also performed and the results stored.
	 *
	 * @param flRequest $request The request object.
	 */
	function processRequest($request) {
		parent::processRequest($request);

		// Ensure that the input is one of the items from the options, only fails if hacking
		if($this->value !== null && !array_key_exists($this->value, $this->options)) {
			$this->isValid = false;
			$this->error = __('Please select a valid item.', 'fusionLib');
		}
	}

	/**
	 * Draw the element.
	 *
	 * @return string The HTML.
	 */
	function render() {
		$html = "<div class=\"selectControl {$this->name}SelectControl\"><select id=\"$this->name\" name=\"$this->name\"" . $this->attribHTML() . ">\n";
		$inGrp = false;
		foreach($this->options as $v => $t) {
			if($this->grpPattern !== null && preg_match($this->grpPattern, $v)) {
				if($inGrp) $html .= '</optgroup>';
				$html .= "<optgroup label=\"$t\">";
				$inGrp = true;
			}
			else {
				$html .= "<option value=\"$v\"";
				if($v == $this->value)
					$html .= ' selected="selected"';
				$html .= ">$t</option>\n";
			}
		}
		if($inGrp) $html .= '</optgroup>';
		return $html . "</select></div>\n";
	}

	/**
	 * Get the elements option list.
	 *
	 * @return array The array of options passed to the constructor.
	 */
	function getOptions() {
		return $this->options;
	}
}
