<?php

/**
 *	DUMP
 *
 */

function dump($data=null) {
	echo '<pre style="text-align: left;border: 1px solid grey; padding: 3px; margin: 0px; background-color: silver;">';
	if ($data !== null) {
		if (is_array($data)) {
			print_r($data);
		}
		elseif (is_object($data)) {
			var_dump($data);
		}
		else {
			echo($data);
		}
	} else {
		
	}
	echo ('</pre>');
}




/**
 *	resolve_request
 *	@param $request_uri 
 *	return array of requests
 */
 
 function resolve_request($request_uri) {
	$arr_request = array();
	if ($_SERVER['REQUEST_URI'] != "/" && $_SERVER['REQUEST_URI'] != '') {
		$arr_request = explode("/",trim($_SERVER['REQUEST_URI'],"/"));
		$get_params = $arr_request[count($arr_request)-1];
//			dump(explode("?",$arr_request[count($arr_request)-1]));
		
		if (preg_match("~^(.*?)\?(.*?)$~",$get_params,$matches)) {
			$arr_request[count($arr_request)-1] = str_replace("?".$matches[2],"",$arr_request[count($arr_request)-1]);
			if ($arr_request[count($arr_request)-1] == '') unset ($arr_request[count($arr_request)-1]);
			$arr_request_tmp = explode("&",$matches[2]);
			parse_str($matches[2],$arr);
			$arr_request['get_params'] = $arr;
		}
		
	}
	//dump($arr_request);
	return $arr_request;
}


/*
 *	function generate form BETA!!!
 *	automatic form generation from array data
 *	
 *
 */

 
 function generate_form($arr,$new_fieldset=true) {
	//dump($arr);
	//dump($showRawField);
	foreach ($arr['tables'] as $table => $item) {
		$table_name = $table;
		$printlabelsfromHR = (isset($arr['hreadable']) && is_array($arr['hreadable'])) ? true : false;
		if ($printlabelsfromHR) {
			$group_name = $arr['hreadable'][$table]['table_hreadable'];
		} else {
			$group_name = $table;
		}
		//dump($table);
		if ($new_fieldset) $out .= '<fieldset><legend>'.$group_name.'</legend>';
		foreach ($item as $field => $ftype) {
			$arr_ftype = explode(";",$ftype);
			//dump($arr_ftype);
			$printlabelsfromHR = (isset($arr['hreadable']) && is_array($arr['hreadable'])) ? true : false;
			if ($printlabelsfromHR) {
				$label = $arr['hreadable'][$table][$field];
				$group_name = $arr['hreadable'][$table]['table_hreadable'];
			} else {
				$label = $table_name.".".$field;
				$group_name = $table;
			}
					
			switch ($arr_ftype[0]) {
				case ('VC'):
				case ('INPUT'):
				case ('TXT'):
					$out .= '<dl><dt><label for="'.$table_name.".".$field.'">'.$label.':</label></dt> <dd><input id="'.$table_name.".".$field.'" name="'.$table_name."|".$field.'" value="" /></dd></dl>';
				break;
				
				case 'PASS':
					$out .= '<dl><dt><label for="'.$table_name.".".$field.'">Geslo:</label></dt> <dd><input type="password" id="'.$table_name.".".$field.'" name="'.$table_name."|".$field.'" value="" /></dd></dl>';
					$out .= '<dl><dt><label for="'.$table_name.".".$field.'-2">Ponovi geslo:</label></dt> <dd><input type="password" id="'.$table_name.".".$field.'-2" name="'.$table_name."|".$field.'-2" value="" /></dd></dl>';
				break;
				
				case 'SE':
					/** PARAMETERS:
					 *	0: type
					 *	1: option list
					 *	2: onchange javascript function
					 **/
					//dump($arr_ftype);
					$forbidden_values = array('','null','false');
					if (isset($arr_ftype[2]) && (!in_array($arr_ftype[2],$forbidden_values))) {
						//javascript onChange function
						//dump($arr_ftype[2]);
						$onchange = ' onChange="'.$arr_ftype[2].'" ';
						//dump($onchange);
					}
					$out .= '<dl><dt><label for="'.$table_name."-".$field.'">'.$label.':</label></dt> <dd><select '.$onchange.'id="'.$table_name."-".$field.'" name="'.$table_name."|".$field.'">';
						$out .= '<option selected="selected" value="-1">-- izberi --</option>';
						foreach ($arr['input_data'][$arr_ftype[1]] as $row) {
							$out .= '<option value="'.$row['id'].'">'.$row['value'].'</option>';
						}
					//$out .= '<input id="'.$table_name.".".$field.'" name="'.$table_name.".".$field.'" value="" />';
					$out .= '</select></dd></dl>';
				break;
			}
			//dump("$table_name.$field => $ftype");
		}
		if ($new_fieldset) $out .= '</fieldset>';
	}
	return $out;
	
	
 }
 
function showActionInfo() {
	global $_MESSAGES;
	global $is_debug;
	//dump($_MESSAGES);
	
	$out = '';
	foreach ($_MESSAGES as $mType => $value) {
		switch ($mType) {
			case 'err':
				$title = "Napaka";
			break;
			
			case 'success':
				$title = "OK";
			break;
			
			case 'debug':
				$title = "debug_info";
			break;
			
			case 'info':
				$title = "";
			break;
		}
		
		if ($mType != 'debug' || ($mType == 'debug' && $is_debug)) {
			$tag = (count($value)>1) ? "ul" : 'div';
			$innertag = (count($value)>1) ? "li" : 'p';
			$out .= "\n".'<div class="messages '.$mType.'">';
			$out .= ($title != '') ? '<h3>'.$title."</h3>" : '';
			$out .= "\n\t<$tag>";
			foreach ($value as $k=>$message) {
				$out.="\n\t\t<$innertag>".$message."</$innertag>";
			}
			$out.= "\n\t</$tag>\n</div>\n";
		}
	}
	return $out;
}


function checkIfExists($sql) {
	$a = new Db();
	if (count($return = $a->select($sql,true))>0) {
		return $return;
	} else {
		return false;
	}
}


function correct_multiple_values($string,$type='mail') {
	//dump($string);
	if ($type=='mail') {
		$separator = "\ ";		//one space
	} elseif ($type=='name') {
		$separator = "\ \ ";	//two spaces
	}
	if (preg_match("~^(.*?)".$separator."+(.*?)$~",$string,$matches)) {
		unset($matches[0]);
		//dump($matches);
		foreach ($matches as $item) {
			//dump(trim($mail));
			//if (is_string($klinika['odgovorna_oseba_mail'])) unset($klinika['odgovorna_oseba_mail']);
			$return[] = trim($item);
		}
	} else {
		$return = array($string);
	}
	return $return;
}



/**
 *	Nov uporabnik
 *	Checks if user already exists (selects by user_email)
 *	Adds user_type
 *	return: user_id of new user
 */
function create_user($user_data,$user_type_id,$location_id=null) {
	//dump($user_data);
	if (is_array($user_data)) {
		//create new user from $user_data
		if (!filter_var($user_data['user_mail'], FILTER_VALIDATE_EMAIL)) {
			return false;
		}
		//validated e-mail string
		$sql = "SELECT * FROM users WHERE user_mail='".$user_data['user_mail']."'";
		
		if (!$return = checkIfExists($sql)) {
			//create new user
			$sql = "
				INSERT INTO users SET 
					user_active = 1, 
					login_name = '".$user_data['login_name']."',
					user_mail = '".$user_data['user_mail']."',
					password = '".$user_data['password']."',
					user_name = '".$user_data['user_name']."',
					user_surname = '".$user_data['user_surname']."'";
					
			$oDb = new Db();
			$user_id = $oDb->save($sql);
			dump("User created: user_id={$user_id}");
		} elseif (count($return) == 1) {
			$user_id = $return[0]['user_id'];
			//dump("User read: user_id={$user_id}");
		} else {
			//več userjev z istim emailom že obstaja v bazi
			die("DUPLICATES!!!");
		}
	} else {
		$user_id = $user_data;
	}
	
	//add user to user_type
	$sql = "SELECT * FROM user_user_type WHERE user_id = {$user_id}";
	//dump($sql);
	if (!$return = checkIfExists($sql)) {
		//make it!
		$sql = "INSERT INTO user_user_type SET user_id = {$user_id}, user_type_id = {$user_type_id}";
		$oDb = new Db();
		$oDb->save($sql);
		dump("user_user_type inserted.");
	} else {
		//user_user_type already exists	
	}
	return $user_id;
}
function get_user_types() {
	$sql = "SELECT * FROM user_types";
	$oDb = new Db();
	return $oDb->select($sql,true);
}
function get_user($detailed=false,$type_id=null) {
	$user_type_where = (is_array($type_id)) ? " IN (".trim(implode(",",$type_id),',').")" : "='{$type_id}'";

	$sql = "SELECT * FROM users";
	if ($detailed) $sql.="
		LEFT JOIN user_user_type ON user_user_type.user_id = users.user_id
		WHERE user_user_type.user_type_id{$user_type_where}
		ORDER BY CONCAT(users.user_surname,users.user_name) ASC
	";
	$oDb = new Db();
	return $oDb->select($sql,true);
}

function get_user_id_by_name($param) {
	global $_MESSAGES;
	$arr = json_decode($param,true);
	//HERE CHECK FOR REPLACED VALUES
	$arr_table = explode(".",$arr['field']);
	$sql = "SELECT {$arr['field']} FROM {$arr_table[0]} WHERE user_name = '{$arr['user_name']}' AND user_surname = '{$arr['user_surname']}'";
	//dump($sql);
	$db = new Db();
	$res = $db->select($sql,true);
	if (count($res) ==1) return $res[0]['user_id'];
		else {
			//dump($sql);
			$_MESSAGES['err'][] = "Ne najdem uporabnika, ali več uporabnikov ima ime '{$arr['user_name']} {$arr['user_surname']}'";
			return false;
		}
}
// function to validate data entered on form fields and checks if all fields are filled

function check_input($data, $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
    {
        die($problem);
    }
    return $data;
}

function render_menu($arr_menu,$tagname='ul',$options=array()) {
	global $REQUEST_URI;
	
	$url = implode('/',$REQUEST_URI);
	$menu = "<$tagname class=\"side_menu\">";
	
	foreach($arr_menu as $key => $name) {
		if ($url == "$options/$key") $class = 'active';
		else $class='';
		$menu .= '<li class="'.$class.'"> <a href="/'.$options.'/'.$key.'/">'.$name.'</a></li>';
	}
	$menu .= '</'.$tagname.">";
	return $menu;
}

function generate_select($sql, $attributes=null){
	$db= new Db();
	$results = $db->select($sql);
	$set="";
	foreach($results as $value){
		$set.="<option value='".$value['id']."'>".$value['value']."</option>";
	}
	$select="<select {$attributes}>{$set}</select>";
	
	return $select;
}
?>