<?php

require_once('dbconfig.php');

class USER
{

	private $conn;

	public function __construct()
	{
		$database = new Database();
		$db = $database->dbConnection();
		$this->conn = $db;
    }

	public function runQuery($sql)
	{
		$stmt = $this->conn->prepare($sql);
		return $stmt;
	}

	public function register($uname,$upass)
	{
		try
		{
			//$new_password = password_hash($upass, PASSWORD_DEFAULT); // 3.2.17 ivan changed to cleartext password saving to make it more easy...
			$new_password = $upass;

			$stmt = $this->conn->prepare("INSERT INTO benutzer(benutzer_name,benutzer_pass) VALUES(:uname, :upass)");

			$stmt->bindparam(":uname", $uname);
			$stmt->bindparam(":upass", $new_password);

			$stmt->execute();

			return $stmt;
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}
	}


	public function doLogin($uname,$upass)
	{
		try
		{
			$stmt = $this->conn->prepare("SELECT benutzer_id, benutzer_name, benutzer_pass FROM benutzer WHERE benutzer_name=:uname");
			$stmt->execute(array(':uname'=>$uname));
			$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
			if($stmt->rowCount() == 1)
			{
				//if(password_verify($upass, $userRow['user_pass'])) // 3.2.17 ivan changed to cleartext password saving to make it more easy...
				if($upass == $userRow['benutzer_pass'])
				{
					$_SESSION['user_session'] = $userRow['benutzer_id'];
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}
	}

	public function is_loggedin()
	{
		if(isset($_SESSION['user_session']))
		{
			return true;
		}
	}

	public function redirect($url)
	{
		header("Location: $url");
	}

	public function doLogout()
	{
		session_destroy();
		unset($_SESSION['user_session']);
		return true;
	}
}
?>
