<?php
namespace engine\eventSubscribers\widgets;

use Subscribers\AbstractEventSubscriber;
class WidgetHandlerEventSubscriber extends AbstractEventSubscriber
{

    public function participationHandle($eventData, $metaParams)
    {
        if (empty($_SESSION["user_id"])) {
            header("Location: ".$_SERVER["HTTP_REFERER"]."?widgetStatus=notLoggedIn");
        }

        if (!empty($_GET["uniq_name"]) && !empty($_SESSION["user_id"])) {
            $uniq_name = $_GET["uniq_name"];
            $user_id = $_SESSION["user_id"];

            $participationId = $this->db->get("participations", "id", ["uniq_name" => $uniq_name]) ?? 0;
            $participationGroup = $this->db->get("participations", "group_id", ["uniq_name" => $uniq_name]) ?? 0;
            $userGroup = $this->db->get("users", "group", ["id" => $user_id]) ?? 0;
            if ($userGroup != $participationGroup) {
                header("Location: ".$_SERVER["HTTP_REFERER"]."?widgetStatus=groupError");
            }

            if (!empty($participationId)) {
                if (!$this->db->get("participation_users", "id", ["user_id" => $user_id, "participation_id" => $participationId])) {
                    $this->db->insert("participation_users", [
                        "participation_id" => $participationId,
                        "user_id" => $user_id,
                        "hash" => hash("sha256", $participationId.$user_id),
                    ]);
                    header("Location: ".$_SERVER["HTTP_REFERER"]."?widgetStatus=success");

                } else {
                    header("Location: ".$_SERVER["HTTP_REFERER"]."?widgetStatus=alreadyParticipated");
                }
            }

        }

    }

    public function quizHandle($eventData, $metaParams)
    {
        if (empty($_SESSION["user_id"])) {
            header("Location: ".$_SERVER["HTTP_REFERER"]."?widgetStatus=notLoggedIn");
        }

        $quizParticipation = [];
        if (!empty($_GET["answer_id"]) && !empty($_SESSION["user_id"])) {
            $answer_id = $_GET["answer_id"];
            $user_id = $_SESSION["user_id"];
            $question_id = $_GET["quiz_question_id"];

            $answeredQuiz = $this->db->get("quiz_participations", "*", ["quiz_question_id" => $question_id, "user_id" => $user_id]);

            if (!empty($answeredQuiz)) {
                $this->db->delete("quiz_participations", ["quiz_question_id" => $question_id, "user_id" => $user_id]);
            }

            $this->db->insert("quiz_participations", [
                "user_id" => $user_id,
                "quiz_question_id" => $question_id,
                "selected_option" => $answer_id,
                "country" => ""
            ]);

            //$quizParticipation = $this->db->select("quiz_participations", "*", ["quiz_question_id" => $question_id]);
            header("Location: ".$_SERVER["HTTP_REFERER"]."?widgetStatus=success");

        }

    }

}