<?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["delete_counter"]) && !empty($_POST["counter_id"])) {
        $db_connect->delete("counters", ["id" => $_POST["counter_id"]]);

        $db_connect->delete("widgets_translations", ["widget_id" => $_POST["counter_id"], "widget_type" => "counter_widget"]);

        header("Location: ".$_SERVER["HTTP_REFERER"]);
    }

    // Получаем список промокодов
    $counters = $db_connect->select("counters", "*", [
        'ORDER' => ['id' => 'DESC']
    ]);

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

    require_once ENGINE_DIR . '/mods/counter_widget.php';
    foreach ($counters as $key => &$counter) {
        $counter[$lang["datatable"]["value"]] = $lang["datatable"]["count"].": ".getCountData($counter["uniq_name"])["objectCount"];
        $counter["db_id"] = $counter["id"];
        $counter["id"] = $key + 1;

        if ($counter["object_type"] == "modules") {
            if ($counter["name"] != "all_modules") {
                $counter[$lang["datatable"]["name"]] = $counter["name"];
            } else {
                $counter[$lang["datatable"]["name"]] = $lang['datatable'][$counter["name"]];
            }
        } else {
            if ($counter["name"] != "all_groups") {
                $counter[$lang["datatable"]["name"]] = "Группа: ".$counter["name"];
            } else {
                $counter[$lang["datatable"]["name"]] = $lang['datatable'][$counter["name"]];
            }
        }

        if ($counter["active"] == 1) {
            $counter[$lang["datatable"]["active"]] = "<div class='form-check form-switch'>
                            <input type='hidden' name='home_tpl' value='true'>
                            <input data-id='{$counter['db_id']}' class='form-check-input offlineswitcher table_active' checked type='checkbox' role='switch' name='active' id='table_active' value='true'>
                        </div>";
        } else {
            $counter[$lang["datatable"]["active"]] = "<div class='form-check form-switch'>
                            <input type='hidden' name='home_tpl' value='false'>
                            <input data-id='{$counter['db_id']}' class='form-check-input offlineswitcher table_active' type='checkbox' role='switch' name='active' id='table_active' value='true'>
                        </div>";
        }

        $counter[$lang["datatable"]["why_count"]] = $lang['datatable'][$counter["counter_sub_object"]];
        $counter[$lang["datatable"]["counter_type"]] = $lang['datatable'][$counter["counter_type"]];
        $counter[$lang["datatable"]["object_type"]] = $lang['datatable'][$counter["object_type"]];
        $counter[$lang["datatable"]["from"]] = $counter["from_count"];
        $counter[$lang["datatable"]["to"]] = $counter["to_count"];
        $counter[$lang["datatable"]["widget_name"]] = $db_connect->get("widgets_translations", "value", ["widget_id" => $counter["db_id"], "widget_type" => "counter_widget", "name" => "widget_name", "lang_code" => $_SESSION["lang"] ?? $config['default_lang']]);
        $counter[$lang["datatable"]["uniq_name"]] = $counter["uniq_name"];

        if ($counter["template_name"] == "auto") {
            $includeText = "{include file=\"templates/{$config["skin"]}/widgets/counter_widget.tpl\" uniqName=\"{$counter["uniq_name"]}\" showTypeName=true prefix=\"/\" }";
        } else {
            $includeText = "{include file=\"templates/{$config["skin"]}/widgets/custom/counter/{$counter["template_name"]}\" customUniqName=\"{$counter["uniq_name"]}\" showTypeName=true prefix=\"/\" }";
        }

        $counter[$lang["datatable"]["actions"]] = "<a href='#' id='copy-ico' data-copy='{$includeText}' class='mx-3 fa fa-copy'></a><a href='/admin?action=widgets/counters/edit&id={$counter['db_id']}' data-id='{$counter['db_id']}' class='mx-1 bg-transparent border' id='edit-counter'><i class='fa fa-edit'></i></a>
                            <form method='POST' action='/admin?action=widgets/counters/list' style='display:inline;'>
                                <input type='hidden' name='form_key' value='{$_SESSION['category_form_key']}'>
                                <input type='hidden' name='counter_id' value='{$counter['db_id']}'>
                                <input type='hidden' name='delete_counter' value='1'>
                                <button type='submit' class='no-b mx-1' name='delete_counter' onclick='return confirm(\"Вы уверены, что хотите удалить счетчик?\");'>
                                    <i class='fa fa-trash'></i>
                                </button>
                            </form>";

    }
    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->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });
    // Устанавливаем массив переменных в Smarty
    $yourData = array('title' => $lang['nav']['counters'] . ' - ' . $config['title']);
    $smarty->assign("counters", $counters);
    $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);
    ?>
