<?php
/**
 * class auth_controller
 *
 * Description for class auth_controller
 *
 * @author:
*/
namespace controller;

use form\auth_login_form;
use form\auth_reminder_form;
use form\auth_reset_form;
use core\exception\databaseException;
use core\controller;
use core\flashMessages;
use core\mail;
use core\password;
use core\url;
use core\user;

class auth_controller extends controller {
	public function __construct() {
		parent::__construct();
	}

	public function login_action() {
		global $__database;

		$url = isset($_GET["url"]) ? $_GET["url"] : "";

		$form = new auth_login_form();
		if($form->valid()) {
			try {
				$query = $__database->prepare("SELECT `user_id`, `name`, `email`, `role`, `password` FROM `users` WHERE `email`=:email AND `active`='1'");
				$query->bindParam(":email", $form->email);
				$query->execute();
				if($record = $query->fetch(\PDO::FETCH_ASSOC)) {
					if(password::verify($form->password, $record["password"])) {
						user::authorization($record["user_id"], $record["name"], $record["email"], $record["role"]);

						if(!empty($url)) {
							url::redirect($url);
						}

						if($record["role"] == "administrator") {
							url::redirectArea("administrator");
						}

						url::redirectAction("prezenter");
					}
				}
			} catch(PDOException $error) {
				throw new databaseException($error->getMessage(), $error->getCode());
			}

			flashMessages::error("Adres e-mail i hasło nie zgadzają się. Sprawdź jeszcze raz i spróbuj ponownie.");
		}

		$this->setVariable("url_redirect", $url);
		return $this->view($form, null, "layout_auth");
	}

	public function reminder_action() {
		global $__database;

		$form = new auth_reminder_form();
		if($form->valid()) {
			try {
				$query = $__database->prepare("SELECT `user_id`, `email` FROM `users` WHERE `email`=:email AND `active`='1'");
				$query->bindParam(":email", $form->email);
				$query->execute();
				if($record = $query->fetch(\PDO::FETCH_ASSOC)) {
					$reminder_id = $__database->newGuid();
					$token = md5(uniqid($record["user_id"].$record["email"], true));

					$query = $__database->prepare("UPDATE `users_reminder` SET `date_expired`=NOW() WHERE `user_id`=:user_id");
					$query->bindParam(":user_id", $record["user_id"]);
					$query->execute();

					$query = $__database->prepare("INSERT INTO `users_reminder` (`reminder_id`, `user_id`, `date_expired`, `token`) VALUES (:reminder_id, :user_id, DATE_ADD(NOW(), INTERVAL 12 HOUR), :token)");
					$query->bindParam(":reminder_id", $reminder_id);
					$query->bindParam(":user_id", $record["user_id"]);
					$query->bindParam(":token", $token);
					$query->execute();

					mail::static_send("Instrukcja zmiany hasła", mail::render_message("password_reminder", array("url" => url::action("nowe-haslo", $token, "", false, true))), $record["email"]);
					
					flashMessages::success("Wiadomość z instrukcją zmiany hasła została wysłana na Twój adres e-mail.");

					url::redirectAction("logowanie");
				}
			} catch(PDOException $error) {
				throw new databaseException($error->getMessage(), $error->getCode());
			}

			flashMessages::error("Adres e-mail nie zgadza się. Sprawdź jeszcze raz i spróbuj ponownie.");
		}

		return $this->view($form, null, "layout_auth");
	}

	public function reset_action($vars) {
		global $__database;
		
		$token = isset($vars["token"]) ? trim(stripslashes($vars["token"])) : "";

		$query = $__database->prepare("SELECT `reminder_id`, `user_id` FROM `users_reminder` WHERE `token`=:token AND `date_expired`>NOW()");
		$query->bindParam(":token", $token);
		$query->execute();
		if(!$record = $query->fetch(\PDO::FETCH_ASSOC)) {
			__debug("Token zmiany hasła wygasł lub nie został odnaleziony");
		}

		$form = new auth_reset_form();
		if($form->valid()) {
			try {
				$password = password::hash($form->password);
				
				$query = $__database->prepare("UPDATE `users` SET `password`=:password WHERE `user_id`=:user_id");
				$query->bindParam(":password", $password);
				$query->bindParam(":user_id", $record["user_id"]);
				$query->execute();

				$query = $__database->prepare("UPDATE `users_reminder` SET `date_expired`=NOW() WHERE `reminder_id`=:reminder_id");
				$query->bindParam(":reminder_id", $record["reminder_id"]);
				$query->execute();

				flashMessages::success("Hasło zostało zmienione. Możesz się już zalogować.");

				url::redirectAction("logowanie");
			} catch(PDOException $error) {
				throw new databaseException($error->getMessage(), $error->getCode());
			}
		}

		return $this->view($form, null, "layout_auth");
	}

	public function logout_action() {
		user::logout();

		url::redirectAction("logowanie");
	}
}
?>