<?php
class UserModel extends Model{
	public $reg;
	public $login;
	protected $name;
	protected $mail;
	protected $psw;
	public function Index(){
		return;
	}
	
	public function login(){
		if(isset($_POST['name'])){
			if(isset($_POST['psw'])){
				$query="SELECT * FROM user WHERE name='".$_POST['name']."'";
				$this->query($query);
				$record=$this->resultSet();
				if (isset($record[0]['pass'])){
					if(sha1($_POST['psw'])==$record[0]['pass']){
						$_SESSION['login']=1;
						$_SESSION['feedback']="Login Erfolgreich";
						$_SESSION['name']=$_POST['name'];
						$_SESSION['admin']=$record[0]['admin'];
						$_SESSION['wichtel']=$this->getwichtel($record[0]['Wichtel']);
						
						header("Location: /user/home");
					}else{
						$_SESSION['feedback']="Login nicht Erfolgreich";
					}
				}else{
					$_SESSION['feedback']="Nutzer unbekannt";
				}
			}
		}else{
			$_SESSION['feedback']="";
		}
	}
	
	public function regis(){
		return $this->reg;
	}
	
	public function register(){
		$this->reg=false;
		if(isset($_POST['regi'])){
			$this->name=$_POST['name'];
			$this->mail=$_POST['mail'];
			$this->psw=$_POST['psw'];
			$psw2=$_POST['psw2'];
			if($this->psw==$psw2){
				// Insert into MySQL
				$this->query('INSERT INTO user (name, mail, pass, berechtigt) VALUES(:name, :mail, :pass, :ber)');
				$this->bind(':name', $this->name);
				$this->bind(':mail', $this->mail);
				$this->bind(':pass', sha1($this->psw));
				$this->bind(':ber', '0');
				$this->execute();
				$_SESSION['reg']=true;
				echo("erfolg");
			}
		}
	}
	
	public function logout(){
		$_SESSION['login']=false;
		$_SESSION['feedback']="Logout erfolgreich";
		header("Location: /home/index");
		
	}
	public function change(){
		if(isset($_POST['old'])){
			if($_POST['new']==$_POST['new2']){
				$pass=sha1($_POST['new']);
				$name=$_SESSION['name'];
				$this->query("UPDATE user SET pass=':pass' WHERE name=':name'");
				$this->bind(':pass', $pass);
				$this->bind(':name', $name);
				$this->execute();
				
			}
		}
	}
	
	public function home(){

	}
}
