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

        $categoryData = $db_connect->get("news_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;
        }


        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $newsList = getFilterDataList("news", $lang_code, null, [
            "n.date"
        ], $categoryData["id"]);
        require_once ENGINE_DIR . '/mods/get_module_categories.php';

        // Получаем alt_names для каждой категории
        foreach ($newsList as &$story) {
            $story['category_alt_names'] = getCategoriesAltNames($story['id'], "news");
            $categories = getCategoriesList($story['id'], "news");
    
            // Декодируем описания новости
            if (!empty($story['short_desc'])) {
                $story['short_desc'] = html_entity_decode($story['short_desc'], ENT_QUOTES, 'UTF-8');
            }
        }

        $categoriesDataList = getModuleCategoriesDataList("news");


        // Рассчитываем количество страниц для пагинации относительно новостей с данной категорией
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $newsPerPage = $config['modules']['news']['news_fromcats_per_page'];
        $totalPages = ceil(count($newsList) / $newsPerPage);
        
        // Определяем, с какой новости начинать отображение на текущей странице
        $start = ($currentPage - 1) * $newsPerPage;
        require_once(ENGINE_DIR . '/mods/pagination.php');
    
        // Передаем данные в Smarty
        $smarty->assign('categoriesDataList', $categoriesDataList);

        $smarty->assign('title', $lang['module_name']['news'] . ' - ' . $config['title']);
        $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/news">' . $lang['module_name']['news'] . '</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('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/modules/news/' . $config['modules']['news']['short_tpl'], ['newsList' => array_slice($newsList, $start, $newsPerPage), 'category_alt_names' => $categoryData['alt_name']]));
    
        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }
    
    $smarty->assign($config);    