<?php
class Member {
	public function Index($params) {
		if (Session::IsUserLoggedIn())
			return $this->Manage($params);
		else
			return $this->Login($params);
	}
	
	public function Login($params){
		if (Session::IsUserLoggedIn()){
			header("location:/member/manage");
			return;
		}
		
		if (!isset($params['email']))
			$params['email']="";
		
		$errors=array();
		
		if (isset($params['permission_error']) && $params['permission_error']==true)
			$errors[]="You don't have permission to access this page.";
		
		if (isset($params['submit_form']) && $params['email']!=""){
			$user=new User($params['email']);
			if ($user->UserId!=null && $user->ValidatePassword($params['password'])){
				Session::SetLoggedInUser($user);
				header("location:/member/manage");
				return;
			}
			
			$errors[]="Unable to log in. Please check your login details and try again.";
		}
		
		return new View("Member/login.view",array(
			"errors"=>$errors,
			"loginEmail"=>$params['email']
		));
	}
	
	public function Logout($params){
		Session::Destroy();
		header("location:/member");
	}
	
	public function Register($params){
		if (!isset($params['email'],$params['password']))
			return $this->Login($params);
		
		$errors=array();
		if ($params['email']=="")
			$errors[]="Email blank";
		if  ($params['password']=="")
			$errors[]="Password blank";
		
		if (!Utils::IsValidEmail($params['email']))
			$errors[]="Invalid email address";
		
		$user=new User($params['email']);
		if ($user->UserId!=0)
			$errors[]="Email already in use";
		
		if (count($errors)>0)
			return new View("Member/login.view",array(
				"errors"=>$errors,
				"registerEmail"=>$params['email']
			));
		
		$user=new User();
		$user->UserEmail=$params['email'];
		$user->UserPassword=$params['password'];
		$user->UserCreated=time();
		$user->Save();
		
		Session::SetLoggedInUser($user);
		
		header("location:/member/manage");
	}
	
	public function Manage($params){
		if (!Session::IsUserLoggedIn()){
			header("location:/member/");
			return;
		}
		
		$user=Session::GetLoggedInUser();
		$errors=array();
		
		if (isset($params['submit_form']) && $params['new_password']!=""){
			if ($params['new_password']==$params['confirm_password']){
				$user->UserPassword=$params['new_password'];
				$user->Save();
				header("location:/member/manage");
				return;
			} else
				$errors[]="Passwords did not match";
		}
		
		return new View("Member/manage.view",array("user"=>$user,"errors"=>$errors));
	}
}
