<?php
function Login($cell,$password){
	
	
	if(!$_POST)	return;
	
	session_start();
	session_unset();
	session_destroy();
	session_start();
	
	/*$allowed_usernames = array('admin');
	if(!empty($cell) && !is_cellulare($cell) && !in_array($cell,$allowed_usernames))
		printMsg('Numero cellulare errato. Inserire solo numeri. Es: 3403000000','warning');
		*/
	$result = $GLOBALS['mysqli']->query("
	SELECT * FROM users 
	LEFT JOIN enti ON users.ente_id = enti.ente_id
	WHERE user_cell=".dbClean($cell)." AND user_pass=".dbClean($password)." AND ente_url = '".$_GET['e']."' AND user_active = 1");

	if($result->num_rows == 1){
		$row = $result->fetch_assoc();
		$_SESSION['user']['id'] = $row['user_id'];
		$_SESSION['user']['nome'] = entities($row['user_nome']);
		$_SESSION['user']['cognome'] = entities($row['user_cognome']);
		$_SESSION['user']['logged'] = true;
		$_SESSION['user']['grp'] = $row['user_grp'];
		$_SESSION['user']['ente_id'] = $row['ente_id'];
		$_SESSION['user']['ente_url'] = $row['ente_url'];
		$_SESSION['user']['ente_anno'] = $row['anno'];
		
		//memorizzo servizi ai quali posso accedere
		if($row['user_services'] <> NULL)
			$my_services = explode(",",$row['user_services']);
			
		$_SESSION['user']['services'] = array();
		$servizi = get_ente_servizi();
		foreach($servizi as $k=>$v){
			if(!$my_services || in_array($v['serv_cod'],$my_services))
				$_SESSION['user']['services'][$v['serv_cod']] = true;
		}

		$GLOBALS['mysqli']->query("UPDATE users SET user_lastaccess = NOW(), user_newcell=0 WHERE user_id=".$row['user_id']);	
		Js('window.location="home/'.$row['user_grp'].'/"');
		die();	
	}else{
		printMsg('Cellulare e/o password errati','danger');
	}

}
?>