<?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.                                                      *
          *****************************************************************************
      */

    // Путь к config.php относительно текущего файла
    require_once(ENGINE_DIR . '/data/config.php');
    require_once(ENGINE_DIR . '/mods/database_helper.php');

    if (isset($_POST["create-quiz"]) && $_POST["form_key"] == $_SESSION["quiz_form_key"]) {
        $question = $_POST["question"];
        $answers = $_POST["answers"];

        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $code = '';

        for ($i = 0; $i < 5; $i++) {
            $code .= $characters[random_int(0, strlen($characters) - 1)];
        }

        $db_connect->insert("quiz", [
            "main_title" => "",
            "type" => $_POST["quiz_type"],
            "by_country" => !($_POST["by_country"] == "false"),
            "price" => (int)$_POST["price"] ?? 0,
            "uniq_name" => $code,
            "template_name" => $_POST["template_name"],
        ]);

        $widgetId = $db_connect->id();

        foreach ($_POST["translations"] as $lng => $translationAssoc) {
            foreach ($translationAssoc as $k => $v) {
                $db_connect->insert("widgets_translations", [
                    "widget_id" => $widgetId,
                    "widget_type" => "quiz_widget",
                    "lang_code" => $lng,
                    "name" => $k,
                    "value" => $v,
                ]);
            }
        }

        $questions = [];
        foreach ($_POST["questions"] as $key => $question) {

            $image = "";
            if (isset($_FILES['question_images'])) {
                $dir = 'uploads/widgets/quiz/'. date('Y') . '/' . date('m') . '/' . uniqid("QUIZ", 15);
                $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/' . $dir;

                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }

                $file_count = count(scandir($uploadDir)) - 1;
                $imageName = $file_count . '_' . basename($_FILES['question_images']['name'][$key][0]);
                $imagePath = $uploadDir . $imageName;

                if (move_uploaded_file($_FILES['question_images']['tmp_name'][$key][0], $imagePath)) {
                    $image = $dir . $imageName;
                } else {
                    $error_message = "Не удалось переместить загруженный файл.";
                }
            }

            $db_connect->insert("quiz_questions", [
                "quiz_id" => $db_connect->id(),
                "question" => $question,
                "image" => $image,
                "settings" => json_encode([]),
            ]);
            $questions[$db_connect->id()] = $key;
        }

        foreach ($questions as $id => $keyId) {
            if (isset($answers[$keyId])) {
                foreach ($answers[$keyId] as $answer) {
                    $db_connect->insert("quiz_answers", [
                        "quiz_question_id" => (int)$id,
                        "answer" => $answer,
                    ]);
                }
            }
        }
        header("Location: /admin?action=widgets/quizes/list");

    }


    if (!isset($_SESSION['quiz_form_key'])) {
        $_SESSION['quiz_form_key'] = uniqid();
    }
    require_once (ENGINE_DIR . '/mods/directory_files_folders.php');
    $fileManager = new FileManager($db_connect);
    $quizCustomTemplates = $fileManager->getFilesAndFolders($_SERVER["DOCUMENT_ROOT"]."/templates/main/widgets/custom/quiz");

    $availableLanguagesList = [];
    foreach ($available_languages as $available_language) {
        $availableLanguagesList[] = [
            "code" => $available_language,
            "name" => $available_language
        ];
    }

    $smarty->assign('langs', $availableLanguagesList);

    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });
    // Устанавливаем массив переменных в Smarty
    $yourData = array('title' => $lang['nav']['quizes'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('quizCustomTemplates', $quizCustomTemplates);

    $smarty->assign('page_name', '
                <li class="breadcrumb-item active">' . $lang['nav']['quizes'] . '</li>
            ');
    $smarty->assign('form_key', $_SESSION['quiz_form_key']);
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);