<?php
/**
 * class reaction_form
 *
 * Description for class reaction_form
 *
 * @author:
*/
namespace area\presentation\form;

use core\form;

class reaction_form extends form {
	private $presentation = null;
	private $slide = null;
	private $userId = null;
	
	public function __construct($presentation, $slideId, $userId, $data = array()) {
		$this->presentation = $presentation;
		$this->userId = $userId;
		
		$this->slide = $this->presentation->slideGetId($slideId);
		if($this->slide === false) {
			exit;
		}
		
		parent::__construct($data);
	}

	public function init() {
		$this->addElement("reaction", array("required"), array_merge(array("-1"), $this->slide["reactions"]));
	}

	public function valid() {
		if(!$this->send) {
			return false;
		}

		$valid = true;

		$this->reaction = $this->getElement("reaction")->getValue();
		if((empty($this->reaction) && $this->reaction !== "0") || !$this->getElement("reaction")->optionExist()) {
			$this->elements["reaction"]->setError("Pole wymagane");
			$valid = false;
		}

		return $valid;
	}

	public function save() {
		global $__database;

		if($this->reaction == "-1") {
			try {
				$query = $__database->prepare("DELETE FROM `boards_reactions` WHERE `board_id`=:board_id, `user_id`=:user_id");
				$query->bindParam(":board_id", $this->slide["board_id"]);
				$query->bindParam(":user_id", $this->userId);
				if($query->execute()) {
					return true;
				}
			} catch(PDOException $error) {

			}

			return false;
		}

		try {
			
			$query = $__database->prepare("INSERT INTO `boards_reactions` (`reaction_id`, `board_id`, `user_id`, `reaction`) VALUES (UUID(), :board_id, :user_id, :reaction) ON DUPLICATE KEY UPDATE `date`=NOW(), `reaction`=:reaction");
			$query->bindParam(":board_id", $this->slide["board_id"]);
			$query->bindParam(":user_id", $this->userId);
			$query->bindParam(":reaction", $this->reaction);
			if($query->execute()) {
				return true;
			}
		} catch(PDOException $error) {
			
		}
		
		return false;
	}
}
?>