<?php
/*
    *****************************************************************************
    * MEGA Digital Space - by MEGA Digital Studio                               *
    * ------------------------------------------------------------------------- *
    * CMS Website:  https://megadigital.space                                   *
    * License:  https://megadigital.space/license                               *
    * Owner:  Giorgi Basharuli                                                  *
    * Contact:  online@megadigital.studio                                       *
    * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
    * Website:  https://megadigital.studio                                      *
    * ------------------------------------------------------------------------- *
    * Description: This file is a part of the MEGA Digital Space CMS system.    *
    * Unauthorized distribution, modification, or commercial use is strictly -  *
    * prohibited without prior written permission.                              *
    * ------------------------------------------------------------------------- *
    * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
    * All rights reserved.                                                      *
    *****************************************************************************
*/

require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");

session_start();

$quiz = [];
$quizQuestions = [];
$quizAnswers = [];
$parsedQuiz = [];
if (!empty($_POST['uniq_name'])) {
    $quiz = $db_connect->get("quiz", "*", ["uniq_name" => $_POST['uniq_name']]);
    if (!empty($quiz)) {
        $quizQuestions = $db_connect->select("quiz_questions", "*", ["quiz_id" => $quiz["id"]]);
        if (!empty($quizQuestions)) {
            foreach ($quizQuestions as &$quizQuestion) {
                $quizAnswers = $db_connect->select("quiz_answers", "*", ["quiz_question_id" => $quizQuestion["id"]]);
                $quizParticipations = $db_connect->select("quiz_participations", "*", ["quiz_question_id" => $quizQuestion["id"]]);

                foreach ($quizParticipations as $quizParticipation) {
                    if ($quizParticipation["user_id"] == $_SESSION["user_id"] ?? 0) {
                        $quizQuestion["answered"] = $quizParticipation["selected_option"];
                    }
                }

                $quizQuestion["answers"] = $quizAnswers;
                $quizQuestion["participations"] = $quizParticipations;
                $quizQuestion["participations_count"] = count($quizParticipations ?? []);
            }
        }
    }

    $parsedQuiz = [
        "user_id" => $_SESSION["user_id"] ?? null,
        "quiz" => $quiz,
        "questions" => $quizQuestions,
    ];
}

echo json_encode($parsedQuiz);