<?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(ENGINE_DIR . '/data/config.php');

    function alleventsController($lang_code) {
        global $db_connect, $smarty, $config, $lang;
    
        // Получаем номер текущей страницы
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
    
        // Рассчитываем с какой записи начать выборку
        $start = ($currentPage - 1) * $config['modules']['events']['events_per_page'];

        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $eventsList = getFilterDataList("events", $lang_code, $start, [
            "n.price", "n.start_date", "n.end_date"
        ]);

        $currentCurrency = getCurrentCurrency();
        $baseCurrency = $config['payment_info']['default_currency'];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        $currentRate = $config['payment_info']['currencies'][$currentCurrency];
        foreach ($eventsList as &$event) {
            $event['converted_price'] = convertPrice($event['price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);
        }
        require_once ENGINE_DIR . '/mods/get_module_categories.php';

        // Для каждого мероприятия получаем категории и их alt_name
        foreach ($eventsList as $key => &$events) {
            require_once ENGINE_DIR . '/mods/access_control.php';
            $isPermitted = checkAssess((int)$events["id"], "events");
            if (!$isPermitted) {
                unset($eventsList[$key]);
                continue;
            }

            $events['category_alt_names'] = getCategoriesAltNames($events['id'], "events");
            $categories = getCategoriesList($events['id'], "events");
    
            // Декодируем описания мероприятия
            if (!empty($events['short_desc'])) {
                $events['short_desc'] = html_entity_decode($events['short_desc'], ENT_QUOTES, 'UTF-8');
            }
    
            if (!empty($events['full_desc'])) {
                $events['full_desc'] = html_entity_decode($events['full_desc'], ENT_QUOTES, 'UTF-8');
            }
        }
        $categoriesDataList = getModuleCategoriesDataList("events");

        // Функция для подсчета общего числа товаров с учетом языка
        function countEvents($lang_code) {
            global $db_connect;
            $count = $db_connect->count('events', [
                'language' => $lang_code
            ]);

            return $count;
        }
        
        // Рассчитываем количество страниц для пагинации
        $totalPages = ceil(countEvents($lang_code) / $config['modules']['events']['events_per_page']);
        require_once(ENGINE_DIR . '/mods/pagination.php');

        $smarty->assign('categoriesDataList', $categoriesDataList);
        // Передаем данные в Smarty
        $smarty->assign('title', $lang['module_name']['events'] . ' - ' . $config['title']);

        require_once(ENGINE_DIR . '/mods/binding_control.php');
        generateBindings("events", '<li class="breadcrumb-item active">'. $lang['module_name']['events'] . '</li>');

        $smarty->assign('currentPage', $currentPage);
        $smarty->assign('totalPages', $totalPages);
        $smarty->assign('pagination', generatePagination($currentPage, $totalPages));
        $smarty->assign('currentCurrency', $currentCurrency);
        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/modules/events/' . $config['modules']['events']['short_tpl'], ['eventsList' => $eventsList]));
    
        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }
    
    $smarty->assign($config);