<?php
/**
 * class result_003_Scales
 *
 * Description for class result_003_Scales
 *
 * @author:
*/
use core\slideResult;

class result_003_Scales extends slideResult {
	public function result() {
		global $__database;

		$return = array(
			"users" => 0,
			"results" => array()
			);
		$result = array(
			"__slide__" => array(
				"avg" => array(
					"value" => 0,
					"percent" => 0
				)
			)
		);
		
		if(count($this->options) == 0) {
			$return["results"] = $result;
			return $return;
		}

		$query = $__database->prepare("SELECT COUNT(DISTINCT `user_id`) AS `users` FROM `results` WHERE `board_id`=:id");
		$query->bindParam(":id", $this->id);
		$query->execute();
		if($row = $query->fetch()) {
			$return["users"] = $row["users"];
		}

		foreach($this->options as $option) {
			$result[$option["id"]] = array(
				"sum" => 0,
				"quantity" => 0,
				"values" => array(),
				"value" => 0,
				"percent" => 0
			);
		}

		$query = $__database->prepare("SELECT `option_id`, `reply`, SUM(`reply`) AS `reply_sum`, COUNT(`result_id`) AS `quantity` FROM `results` WHERE `board_id`=:id GROUP BY `option_id`, `reply`");
		$query->bindParam(":id", $this->id);
		$query->execute();
		while($row = $query->fetch()) {
			if(!isset($result[$row["option_id"]])) {
				continue;
			}

			$result[$row["option_id"]]["sum"] += $row["reply_sum"];
			$result[$row["option_id"]]["quantity"] += $row["quantity"];
			$result[$row["option_id"]]["values"][] = array("key" => $row["reply"], "quantity" => $row["quantity"]);
		}

		$sumAll = 0;
		foreach($result as $key => $r) {
			if($key == "__slide__") {
				continue;
			}

			if($result[$key]["sum"] == 0 || $result[$key]["quantity"] == 0) {
				continue;
			}

			$result[$key]["value"] = $result[$key]["sum"] / $result[$key]["quantity"];
			$result[$key]["percent"] = ($result[$key]["value"] / $this->config["max_value"]) * 100;

			$sumAll += $result[$key]["value"];

			$result[$key]["value"] = round($result[$key]["sum"] / $result[$key]["quantity"], 1);
		}

		$result["__slide__"]["avg"]["value"] = $sumAll / count($this->options);
		$result["__slide__"]["avg"]["percent"] = ($result["__slide__"]["avg"]["value"] / $this->config["max_value"]) * 100;
		
		$return["results"] = $result;

		return $return;
	}
}
?>