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

use core\database;
use core\flashMessages;
use core\url;
use form\auth_code_form;

class index_controller extends _controller {
	public function index_action() {
		global $__database;

		$error = false;

		$form = new auth_code_form();
		if($form->valid()) {
			try {
				$code = str_replace(" ", "", $form->code);

				$query = $__database->prepare("SELECT `presentation_id`, `tempo`, `isOpen` FROM `presentations` WHERE `accessKey`=:key");
				$query->bindParam(":key", $code);
				$query->execute();
				if($record = $query->fetch(\PDO::FETCH_ASSOC)) {
					if(($record["tempo"] == "1" && $record["isOpen"] == "1") || $record["tempo"] == "2") {
						$_SESSION["authPresentation"][$record["presentation_id"]] = array(
							"auth" => true,
							"userId" => $this->setNewKey(),
							"userName" => ""
						);

						url::redirect(url::root()."p/".$record["presentation_id"]);
					}

					flashMessages::error("Quiz nie jest otwarty. Poczekaj, aż prezenter ją aktywuje.");
					$error = true;
				}
			} catch(PDOException $error) {
				throw new databaseException($error->getMessage(), $error->getCode());
			}

			if(!$error) {
				flashMessages::error("Nie można znaleźć prezentacji.");
			}
		}

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

	private function setNewKey() {
		global $__database;

		try {
			$newKey = database::newGuid();

			$query = $__database->prepare("INSERT INTO `results_users` (`user_id`) VALUES (:user_id)");
			$query->bindParam(":user_id", $newKey);
			if($query->execute()) {
				return $newKey;
			}
		} catch(PDOException $error) {
			throw new databaseException($error->getMessage(), $error->getCode());
		}

		return false;
	}
}
?>