<?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 eventsByCategoryController($category, $lang_code) {
        global $db_connect, $smarty, $config, $lang;

        $categoryData = $db_connect->get("events_categories", "*", ["alt_name" => $category]);

        if (!$categoryData) {
            // Категория не найдена, отображаем ошибку 404
            header("HTTP/1.0 404 Not Found");
            $smarty->assign('error_message', 'Категория не найдена');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
            exit;
        }
        $categorySearch = '%' . $categoryData['name'] . '%';

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

        // Обработка смены валюты
        $currentCurrency = getCurrentCurrency();
        $baseCurrency = $config['payment_info']['default_currency'];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        $currentRate = $config['payment_info']['currencies'][$currentCurrency];
    
        // Получаем alt_names для каждой категории
        foreach ($eventsList as &$event) {
            $event['converted_price'] = convertPrice($event['price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);

            $event['category_alt_names'] = getCategoriesAltNames($event['id'], "events");
            $categories = getCategoriesList($event['id'], "events");

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

        // Рассчитываем количество страниц для пагинации относительно товаров с данной категорией
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $eventsPerPage = $config['modules']['events']['events_fromcats_per_page'];

        require_once(ENGINE_DIR . '/mods/pagination.php');
        $totalPages = ceil(count($eventsList) / $eventsPerPage);
    
        // Определяем, с какой новости начинать отображение на текущей странице
        $start = ($currentPage - 1) * $eventsPerPage;
    
        // Передаем данные в Smarty
        $smarty->assign('categoriesDataList', $categoriesDataList);
        $smarty->assign('title', $lang['module_name']['events'] . ' - ' . $config['title']);
        $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/events">' . $lang['module_name']['events'] . '</a></li>
            <li class="breadcrumb-item active">' . $categoryData['name'] . '</li>
        ');
        $smarty->assign('currentPage', $currentPage);
        $smarty->assign('totalPages', $totalPages);
        $smarty->assign('pagination', generatePagination($currentPage, $totalPages));
        $smarty->assign('currentCurrency', $currentCurrency);
        $smarty->assign('eventsList', array_slice($eventsList, $start, $eventsPerPage));
        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/modules/events/' . $config['modules']['events']['short_tpl'], ['eventsList' => array_slice($eventsList, $start, $eventsPerPage), 'category_alt_names' => $categoryData['alt_name']]));
    
        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }
    
    $smarty->assign($config);    