<?php
/**
 * class form
 *
 * Description for class form
 *
 * @author:
*/
namespace core;

class form {
	protected $elements = array();
	protected $send = false;

	public function __construct($data = array()) {
		$this->init();
		$this->setInitData($data);
	}

	public function setInitData($data) {
		if(count($this->elements) == 0) {
			__debug("Form is empty!");
		}

		$this->send = isset($_POST["__action"]) ? true : false;

		if($this->send) {
			$data = $_POST;
		}
		
		if(count($data) > 0) {
			foreach($this->elements as $element_name => $element) {
				$value = isset($data[$element_name]) && ((!is_array($data[$element_name]) && strlen($data[$element_name]) > 0) || (is_array($data[$element_name]) && count($data[$element_name]) > 0)) ? $data[$element_name] : "";
				
				$this->elements[$element_name]->setValue($value);
				$this->{$element_name} = $value;
			}
		}
	}

	public function init() {
		
	}

	public function valid() {
		if(!$this->send) {
			return false;
		}

		return true;
	}

	public function getElement($name) {
		if(!isset($this->elements[$name])) {
			return false;
		}

		return $this->elements[$name];
	}

	public function addElement($name, $valid = array(), $options = array()) {
		if(isset($this->elements[$name])) {
			return false;
		}

		$this->elements[$name] = new formElement($options);
	}

	public function getAllErrors() {
		$errors = array();

		foreach($this->elements as $element_name => $element) {
			if(!$element->isError()) {
				continue;
			}

			$errors[$element_name] = $element->getError();
		}

		return $errors;
	}
}

class formElement {
	private $value = "";
	private $options = array();
	private $error = false;
	private $error_message = "";

	public function __construct($options = array()) {
		$this->options = $options;
	}

	public function getValue() {
		return $this->value;
	}

	public function getError() {
		return $this->error_message;
	}

	public function setValue($value) {
		$this->value = $value;
	}

	public function setError($message) {
		$this->error = true;
		$this->error_message = $message;
	}

	public function isError() {
		return $this->error;
	}

	public function optionExist() {
		if(array_search($this->value, $this->options) !== false) {
			return true;
		}

		return false;
	}

	public function isChecked($value) {
		if(!empty($this->value) && array_search($value, $this->value) !== false) {
			return true;
		}

		return false;
	}
}
?>