<?php
/**
 * Validador para el registro de un usuario
 *
 */
class RegistroValidador extends Validator {
	
	protected $required;
	protected $useLabels = true;

	/**
	 * Pass each field to be validated as a seperate argument
	 * to the constructor of this object. (an array of elements are ok)
	 */
	function __construct() {
		//$this->required = array('FirstName', 'Surname', 'Documento', 'FNacimiento', 'Email');
            $this->required = array('FirstName', 'Surname', 'Email');

		parent::__construct();
	}

	public function useLabels($flag) {
		$this->useLabels = $flag;
	}

	/**
	 * Clears all the validation from this object.
	 */
	public function removeValidation(){
		$this->required = null;
	}

	/**
	 * Debug helper
	 */
	function debug() {
	 if(!is_array($this->required)) return false;

	 $result = "<ul>";
	 foreach( $this->required as $name ){
	 	$result .= "<li>$name</li>";
	 }

	 $result .= "</ul>";
	 return $result;
	}

	function javascript() {
		$js = "";
		$fields = $this->form->Fields();
		$dataFields = $this->form->Fields()->dataFields();
		if($dataFields) {
			foreach($dataFields as $field) {
				// if the field type has some special specific specification for validation of itself
				$validationFunc = $field->jsValidation();
				if($validationFunc) $js .= $validationFunc . "\n";
			}
		}
		$useLabels = $this->useLabels ? 'true' : 'false';

		if($this->required) {
			foreach($this->required as $field) {
				if($fields->dataFieldByName($field)) {
					//$js .= "\t\t\t\t\trequire('$field', false, $useLabels);\n";
					$js .= <<<JS
						if(typeof fromAnOnBlur != 'undefined'){\n
							if(fromAnOnBlur.name == '$field')\n
								require(fromAnOnBlur);\n
						}else{
							require('$field');
						}
JS;
				}
			}
		}

		return $js;
	}


	/**
	* Allows validation of fields via specification of a php function for validation which is executed after
	* the form is submitted
	*/
	function php($data) {
		$valid = true;

		$fields = $this->form->Fields();
		foreach($fields as $field) {
			$valid = ($field->validate($this) && $valid);
		}
		if($this->required) {
			foreach($this->required as $fieldName) { 
				$formField = $fields->dataFieldByName($fieldName); 
				if($formField && !$data[$fieldName]) {
					$errorMessage = sprintf(_t('Form.FIELDISREQUIRED').'.', strip_tags('"' . ($formField->Title() ? $formField->Title() : $fieldName) . '"'));
					if($msg = $formField->getCustomValidationMessage()) {
						$errorMessage = $msg;
					}
					$this->validationError(
						$fieldName,
						$errorMessage,
						"required"
					);
					$valid = false;
				}
			}

		}

		if ($valid) {
		  //comprueba que el DNI es correcto
		  /*$formField = $fields->dataFieldByName('Documento');
		  if (!$this->valida_dni($formField->Value())) {
		    $this->validationError('Documento','El valor no es correcto','required');
		    $valid = false;
		  }*/  
		  
		  //comprueba que no exista el ususario
		  $formField = $fields->dataFieldByName('Email');
		  $usuario = DataObject::get_one('UsuarioBtMalaga', "Email='".$formField->Value()."'");
		  if ($usuario != null) {
		  	$this->validationError('Email','El Email introducido ya está siendo utilizado por un usuario','required');
		    $valid = false;
		  }
		  
		  //comprueba que se selecciona un sistema
		  if (!isset($data['Sistemas'])) {
		  	$this->validationError('TextoSistemas','Debe seleccionar al menos un sistema','required');
		    $valid = false;
		  }
		  
		}  

		return $valid;
	}

	/**
	 * Add's a single required field to requiredfields stack
	 */
	function addRequiredField( $field ) {
		$this->required[] = $field;
	}

	function removeRequiredField($field) {
		for($i=0; $i<count($this->required); $i++) {
			if($field == $this->required[$i]) {
				unset($this->required[$i]);
			}
		}
	}

	/**
	 * allows you too add more required fields to this object after construction.
	 */
	function appendRequiredFields($requiredFields){
		$this->required = array_merge($this->required,$requiredFields->getRequired());
	}

	/**
	 * Returns true if the named field is "required".
	 * Used by FormField to return a value for FormField::Required(), to do things like show *s on the form template.
	 */
	function fieldIsRequired($fieldName) {
		return in_array($fieldName, $this->required);
	}

	/**
	 * getter function for append
	 */
	function getRequired(){
		return $this->required;
	}
	
	// retorna false(0) si hay errror o el DNI validado y con letra si no hay error
	private function valida_dni($dni)    {   
      $str = trim($dni);   
      $str = str_replace("-","",$str);   
      $str = str_ireplace(" ","",$str);   
      $n = substr($str,0,strlen($str)-1);   
      $n = intval($n);   
      if (!is_int($n)) {   
         return 0;   
      }   
      $l = substr($str,-1);   
      if (!is_string($l)) {   
         return 0;   
      }   
      $letra = substr ("TRWAGMYFPDXBNJZSQVHLCKE", $n%23, 1);   
      if ( strtolower($l) == strtolower($letra)) {   
        return $n.$l;   
      } else {   
        return 0;   
      }  
   }	
}

?>