<?php

class Tag_Select extends Tag
{
	public function __construct($name=NULL, $options=NULL, $attributes=array())
	{
		parent::__construct('select', $attributes, TAG_CR | TAG_CLOSE);
		if( !is_null($name) )
			$this->attr('name', $name);
		if( !is_null($name) && !array_key_exists('id', $this->attributes) )
			$this->attr('id', Tag::stripId($name));

		// Only process the constructor argument if it is provided
		if( is_array($options) )
		{
			// Add All Options as children of the parent select input
			$this->setOptions($options);
		}

		// Explicitly set the value if provided in the attributes array
		if( is_array($attributes) && array_key_exists('value',$attributes) )
		{
			$this->value($attributes['value']);
		}
	}

	public function setOptions($options)
	{
		if( is_array($options) )
		{
			foreach( $options as $value => $label )
					$this->addChild( new Tag_Option($value, $label) );
		}
		else
			throw new Exception('$options parameter provided to Tag_Select->setOptions function was NOT an array.');
	}

	public function attr($name, $value=NULL)
	{
		if( $name == 'value' )
			return $this->value($value);
		else
			return parent::attr($name, $value);
	}

	// When setting the value of a select tag, the options have to be iterated and modified
	public function value($value=NULL)
	{
		foreach($this->children as $i => $child)
		{
			// If its an object and the class is Tag_Option, then we can change it,
			// for all other cases ignore this child and move to the next one
			if( is_object($child) && $child instanceof Tag_Option )
			{
				if( is_null($child->value()) || $child->value() == '' )
				{
					// Very Specific, Type Checking Test
					$child->selected( ($child->value() === $value ) );
				}
				else
				{
					// Less Restrictive, "Loose" type test
					$child->selected( ($child->value() == $value) );
				}
			}
		}
	}
}
