<?php
require DIR_FS_ADMIN.DIR_WS_CLASSES.'class.dbform_field.php';
class dbform
{
	var $table,$fields,$conn,$action,$mode,$submitted,$db_values,$fields_array,$index_field,$select_id,$no_view_fields;
	var $submit_errors = array();
	var $input_field_class = 'dbforminput';
	
	function dbform($table,$id,$conn){
		$this->table = $table;
		$this->index_field = $id;
		$this->conn = $conn;
		$this->set_fields();
	}

	function set_fields(){
		$fields_query = $this->conn->Execute("SHOW fields FROM ".$this->table);
		while($field = $fields_query->FetchRow()){
			$this->fields[$field['Field']] = new dbform_field($field);
		}
	}
	
	/**
	  * adds a field to the form-fieldset
	  *
	  * @author		mario aspeleiter
	  * @version	1.0
	  * @param String $field The id for the new Field
	  * @param String $type The type pf the new Field
	  * @param Boolean $extern_table Input is not a recordset of source Table. Default false
	  * 
	  */
	function add_field($field,$type,$extern_table = false){
		$field_array = array('Field'=>$field,'Type'=>$type);
		$this->fields[$field] = new dbform_field($field_array,$extern_table);
	}
	
	/**
	 * adds a hidden field to the form-fieldset
	 *
	 * @param string $field
	 * @param string $value
	 * @param boolean $extern_table
	 */
	function add_hidden_field($field,$value,$extern_table = false){
		$field_array = array('Field'=>$field,'Type'=>'hidden');
		$this->fields[$field] = new dbform_field($field_array,$extern_table);
		$this->fields[$field]->visible = true;
		$this->fields[$field]->set_default_value($value);
	}


	function get_db_value($name){
		return $this->db_values[$name];
	}

	function get_value($field){
		if($this->submitted and isset($_POST[$field->name])){
			return $_POST[ $field->name ];
		}else{
			if(xtc_not_null($field->default_value)){
				return $field->get_default_value();
			}
			if($this->mode == 'add'){
				return $field->get_default_value();
			}else{
				return $this->get_db_value($field->name);
			}
		}
	}

	function get_array_values_from_db($field,$params){
		$values = array();
		$query_raw = sprintf("SELECT %s FROM %s WHERE %s='%s'",$field,$params['table'],$params['target'],$this->select_id);
		$query = xtc_db_query($query_raw);
		while($row = xtc_db_fetch_array($query)){
			$values[] = $row[$field];
		}
		return $values;
	}

	function get_array_values_from_request($field){
		$values = array();
		for($i=0;$i<sizeOf($_POST[$field]);$i++){
			$values[] = $_POST[$field][$i];
		}
		return $values;
	}

	function set_input_fields(){
		foreach($this->fields as $k=>$field){
			if($field->get_array() != true){
				$field->set_value( $this->get_value( $field ) );
			}else{
				if($this->mode == 'edit'){
					$values = $this->get_array_values_from_db( $field->name,$field->get_array_allocation() );
				}else if($this->mode == 'add' and $this->submitted){
					$values = $this->get_array_values_from_request( $field->name );
				}
				if($values)
					$field->set_value($values);																											
			}
			$field->set_input_field();
		}
	}

	function validate_input($func,$value){
		switch($func){
			case 'valid_email_address':
				return xtc_validate_email($value);
				break;
			case 'code':
				if(preg_match('#^[a-z_]+$#i',$value)){
					return true;
				}else{
					return false;
				}
				break;
			case 'int':
				if(preg_match('#^[0-9]+$#i',$value)){
					return true;
				}else{
					return false;
				}
				break;
			case 'float':
				if( number_format($value,2,'.','') ==      number_format(floatval($value),2,'.','') ){
					return true;
				}else{
					return false;
				}
				break;
		}
	}
	

	function validate_post_data(){
		foreach($this->fields as $field){
			if($field->visible){
				if($field->get_array() != true){
					if(!isset($_POST[$field->name]) or strlen($_POST[$field->name])<$field->min_length){
						if($field->required == true){
							$field->errors = true;
							$this->submit_errors[] = $field->title;
						}
					}
					if($field->validate_func != ''){
						if(!$this->validate_input($field->validate_func,$_POST[$field->name])){
							$field->errors = true;
							$this->submit_errors[] = $field->title;
						}
					}
				}else{
					for($i=0;$i<sizeOf($_POST[$field->name]);$i++){
						if(!isset($_POST[$field->name][$i]) or strlen($_POST[$field->name][$i])<$field->min_length){
							if($field->required == true){
								$field->errors = true;
								$this->submit_errors[] = $field->title;
							}
						}
						if($field->validate_func != ''){
							if(!$this->validate_input($field->validate_func,$_POST[$field->name][$i])){
								$field->errors = true;
								$this->submit_errors[] = $field->title;
							}
						}
					}
				}
			}
		}
		if(is_array($this->submit_errors) and sizeOf($this->submit_errors)>0)
			return false;
		else
			return true;
	}

	/**
	 * set the db values for selected id
	 *
	 */
	function do_query(){
		$res = $this->conn->Execute("SELECT * FROM ".$this->table." WHERE ".$this->index_field."='".$this->select_id."'");
		$this->db_values = $res->FetchRow();
	}

	/**
	 * get the form-html
	 *
	 * @param string $form_name
	 * @param string $page
	 * @param string $mode add or edit
	 * @param string $template
	 * @param object $smarty
	 * @return string
	 */
	function get_form($form_name,$page,$mode,$template,$smarty){

		$this->mode = $mode;
		$smarty->assign('TEXT_ADD_ELEMENT',TEXT_ADD_ELEMENT);
		$smarty->assign('TEXT_REMOVE_ELEMENT',TEXT_REMOVE_ELEMENT);
		if($mode == 'edit'){
			$this->do_query();
		}
		
		if($_POST['action'] == $mode){
			$this->submitted = true;
		}

		$this->set_input_fields();
		
		if($_POST['action'] == $mode){
			// submitted
			if($this->validate_post_data())
				return 'save';
		}


		$this->sort_items();
		$smarty->assign('FORM_NAME',$form_name);
		
		// AJAX LIST INPUT ADDON
		$ajax_list_input_functions = array();
		$ajax_list_input_functions_double = array();
		for($i=0;$i<sizeOf($this->fields_array);$i++){
			if($this->fields_array[$i]['ajax_function'] && !in_array($this->fields_array[$i]['ajax_function'],$ajax_list_input_functions_double)){
				$ajax_list_input_functions[] = array('func'=>$this->fields_array[$i]['ajax_function'],'title'=>$this->fields_array[$i]['title']);
				$ajax_list_input_functions_double[] = $this->fields_array[$i]['ajax_function'];
			}
		}
		if(sizeOf($ajax_list_input_functions)>0){
			$smarty->assign('ajax_list_input_functions',$ajax_list_input_functions);
			$smarty->assign('ajax_list_input_form',$form_name);
		}
		
		
		$get_params = ($mode == 'edit') ? 'id='.$this->select_id : '';
		$smarty->assign('FORM',xtc_draw_form($form_name,$page,$get_params,'POST','onSubmit="return validate_form(\''.$form_name.'\');"'));
		$smarty->assign('action',xtc_draw_hidden_field('action',$mode));
		$smarty->assign('MODE',$mode);
		$smarty->assign('MAXLENGTH_STRING',TEXT_MAXLENGTH_STRING);
		$smarty->assign('MINLENGTH_STRING',TEXT_MINLENGTH_STRING);
		$smarty->assign('CLICK_ACTION',TEXT_CLICK_ACTION);
		$smarty->assign('REQUIRED_STRING','*');
		$smarty->assign('REQUIRED_INTRO',TEXT_FIELD_REQUIRED);
		$smarty->assign('ERROR_STRING',INPUT_ERROR);
		if($this->submitted)
			$smarty->assign('FORM_INPUT_ERRORS',FORM_INPUT_ERRORS);
		$smarty->assign('SAVE_BUTTON','<input type="submit" value="'.IMAGE_SAVE.'" title="'.IMAGE_SAVE.'" class="'.$this->input_field_class.'">');
		$smarty->assign('JS_REQUIRED_FIELDS',JS_REQUIRED_FIELDS);
		switch($mode){
			case 'add':
				break;
		}

		$smarty->assign('fields',$this->fields_array);
		return $smarty->fetch($template);
	}


	function get_view($page,$print,$template,$smarty){

		$this->do_query();
		$this->set_view_fields_array();
		$this->sort_items(false);
		$smarty->assign('print',$print);
		$smarty->assign('date_format',DATE_FORMAT_SHORT);
		$smarty->assign('MODE','view');
		$smarty->assign('fields',$this->fields_array);
		return $smarty->fetch($template);
	}
	
	function set_view_fields_array(){
		$this->fields_array = array();
		foreach($this->fields as $k=>$field){
			if(!in_array($field->name,$this->no_view_fields)){
				$field->set_value( $this->get_value($field) );
				$array = $field->toArray($view_mode = true);
				if($array and is_array($array))
					$this->fields_array[] = $array;
			}
		}
	}
	
	function field_objects2array(){
		foreach($this->fields as $k=>$field){
			$array = $field->toArray();
			if($array and is_array($array))
				$this->fields_array[] = $array;
		}
	}

	function sort_items($convert_to_array = true){
		if($convert_to_array)
			$this->field_objects2array();
		$this->fields_array = $this->record_sort($this->fields_array,'sort_order');
	}

	function record_sort($array, $id="id", $sort_ascending=true) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
            	if (isset($item[$id])) {
            		if ($array[$lowest_id][$id]) {
            			if (strtolower($item[$id]) < strtolower($array[$lowest_id][$id])) {
            				$lowest_id = $index;
            			}
            		}
                }
                $index++;
            }// end foreach
            
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        } // end while
        
        if ($sort_ascending) {
            return $temp_array;
        } else {
            return array_reverse($temp_array);
        }
	}
	
	/**
	 * get the sql array for the source table
	 *
	 * @param array $request the get/post request
	 * @return Array
	 */
	function get_sql_array($request){
		$sql_array = array();
		foreach($this->fields as $field){
			if( $field->index != '1' and $field->visible and !$field->extern_table){
				if( $field->type == 'datetime'){
					$sql_array[$field->name] = $request[ $field->name ].' '.$request[ $field->name.'_hour' ].':'.$request[ $field->name.'_minute' ];
				}else{
					$sql_array[$field->name] = $request[ $field->name ];
				}
			}
		}
		return $sql_array;
	}
	
}
