<?php

	class RedBean_Exception_Validation extends RedBean_Exception {} 
	
	class Validation extends RedBean_SimpleModel {	
		
		/**
		 * Prepare validator
		 */
		public function dispense() {
			$this->bean->setMeta('rules',array());
		}
		
		/**
		 * Validate on update, if validation failed it will throw an Exception .
		 */
		public function update() {
			$rules = $this->bean->getMeta('rules');
			$data = $this->bean->export();
			
			$errors = validateFields($data, $rules); 
			$error_count = count($errors);
			$this->bean->setMeta('errors',$errors);
			
			if (count($errors) > 0) {
				
				$errors_msg = "<br/><strong>Validation&nbsp;message:</strong><div style='margin:0px 0px 0px 60px;'><ul style='margin:0px 0px 0px -34px;'><li>";
				$errors_msg .= implode("</li><br/><li>",$errors);
				$errors_msg .= "</ul>";
				$errors_msg .= "<br/>Please use try-catch at <pre style='display:inline;'>R::store</pre> to catch the error,".
								" and use <br/><pre style='display:inline;'>$".$this->bean->getMeta('type')." = R::dispense('".$this->bean->getMeta('type')."');\n$".$this->bean->getMeta('type')."->getMeta('errors')</pre><br/> to get the error message"
								.($error_count > 1 ? "s." : "."."</div>");
				
				throw new RedBean_Exception_Validation("Validation Failed. Total field that don't pass validation: $error_count field" . ($error_count > 1 ? "s." : ".").$errors_msg);
			}
		}
		
		/**
		 * Validate presence of columns. 
		 * 
		 * @param string 	$column,...	columns to validate
		 * @param array 	$column 	array of columns to validate 
		 * @param string 	$msg		custom error message (only if first parameter is array) 
		 * @param array 	$msg		custom error messages (only if first parameter is array) 	
		 *  
		 */
		public function validates_presence_of() {
			$first = func_get_arg(0);
			$msg_template = "[field] is required.";
			$rules = $this->bean->getMeta('rules');
			
			if (is_array($first)) {
				try { $msg_template = func_get_arg(1); } 
				catch (Exception $e) {}
					
				$i = 0;
				foreach ($first as $column) {
					$col_msg = (is_array($msg_template) ? $msg_template[$i] : $msg_template);
					$msg = str_replace("[field]",$column,$col_msg);
					$rules[] = "required,$column,$msg";
					$i++;
				}				
			} else {
				$columns = func_get_args();
				
				foreach ($columns as $column) {
					$msg = str_replace("[field]",$column,$msg_template);
					$rules[] = "required,$column,$msg";
				}
			}
			$this->bean->setMeta('rules',$rules);
		}
	}

?>
