<?php

if(!isSession()){
	logout("nosession");
}
else{
	$session_id = getSession();
	$ip = $_SERVER['REMOTE_ADDR'];

	$result_session = 0;
	if($stmt1 = $mysqli -> prepare("SELECT `uid`, `username`, `current_login`, `last_login`, `remember`, `force_change` FROM `login` WHERE `session_id`=?")){
		$stmt1 -> bind_param('s', $session_id);
		$stmt1 -> execute();
		$stmt1 -> bind_result($userid, $username, $session_time, $last_login, $remember, $force_change);
		while($result1 = $stmt1 -> fetch()){ 		
			$result_session += 1;
		}
		$stmt1 -> close();
	}
		

	if($result_session<1){
		logout("nosession");
	}

	elseif($result_session==1){

		$session_time = date_create($session_time);

		$curr_time = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') .' +7 hour'));
		$curr_time = date_create($curr_time);

		$interval = date_diff($session_time, $curr_time, false);
		$interval = $interval->format('%H:%I:%S');

		if(strtotime($interval) < strtotime(SESSION_TIME) || $remember == 1){
			if($stmt1 = $mysqli -> prepare("UPDATE `login` SET `current_login`=(NOW() + INTERVAL 7 HOUR) WHERE `uid`=?")) {
					$stmt1 -> bind_param('i', $userid);
					$stmt1 -> execute();
					$stmt1 -> close();
			}	

			//Load everything from the user
			if($stmt1 = $mysqli -> prepare("SELECT first_name, last_name, username, email, radiotoken FROM login LEFT JOIN users ON users.uid = login.uid WHERE login.uid = ?")){
				$stmt1 -> bind_param('i', $userid);
				$stmt1 -> execute();
				$stmt1 -> bind_result($first_name, $last_name, $username, $useremail, $radiotoken);
				$stmt1 -> fetch();
				$stmt1 -> close();
			}
		}else{
			logout("session");
		}
	}
	else{
		logout("error");
	}
}
?>
