<?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-counter"])) {

        $name = "";
        if ($_POST["object_type"] == "modules") {
            $name = $_POST["module_name"];
        } elseif ($_POST["object_type"] == "user_groups") {
            $name = $_POST["user_group_name"];
        }

        $db_connect->insert("counters", [
            "uniq_name" => generateUniqueCode(),
            "name" => $name,
            "widget_name" => $_POST["widget_name"],
            "counter_type" => $_POST["counter_type"],
            "object_type" => $_POST["object_type"],
            "counter_sub_object" => $_POST["counter_sub_object"],
            "from_count" => $_POST["from_count"] == "" ? 0 : $_POST["from_count"],
            "to_count" => $_POST["to_count"] == "" ? 0 : $_POST["to_count"],
            "active" => $_POST["active"] == "true",
            "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" => "counter_widget",
                    "lang_code" => $lng,
                    "name" => $k,
                    "value" => $v,
                ]);
            }
        }

        header("Location: /admin?action=widgets/counters/list");
    }

    function generateUniqueCode() {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $code = '';

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

        return $code;
    }

    $activeModules = [];
    foreach ($config['modules'] as $moduleName => $moduleConfig) {
        if ($moduleConfig['used'] === true) {
            $activeModules[] = $moduleName;
        }
    }

    require_once (ENGINE_DIR . '/mods/directory_files_folders.php');
    $fileManager = new FileManager($db_connect);
    $counterCustomTemplates = $fileManager->getFilesAndFolders($_SERVER["DOCUMENT_ROOT"]."/templates/main/widgets/custom/counter");

    $staticPages = $db_connect->select("static_pages", "*");
    $groups = $db_connect->select("roles", "*");

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

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

    // Устанавливаем массив переменных в Smarty
    $yourData = array('title' => $lang['nav']['counters'] . ' - ' . $config['title']);
    $smarty->assign("activeModules", $activeModules);
    $smarty->assign("staticPages", $staticPages);
    $smarty->assign("counterCustomTemplates", $counterCustomTemplates);

    $smarty->assign("groups", $groups);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
                <li class="breadcrumb-item active">' . $lang['nav']['counters'] . '</li>
            ');
    $smarty->assign('form_key', $_SESSION['category_form_key']);
    $yourData = array('title' => $lang['nav']['adscategorieslist'] . ' - ' . $config['title']);
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);