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

        // Получаем номер текущей страницы
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Рассчитываем с какой записи начать выборку
        $start = ($currentPage - 1) * $config['modules']['news']['news_per_page'];
        $moduleName = "news";

        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $newsList = getFilterDataList($moduleName, $lang_code, $start, [
            "n.date"
        ]);

        // Для каждой новости получаем категории и их alt_name
        require_once ENGINE_DIR . '/mods/get_module_categories.php';

        foreach ($newsList as $key => &$news) {
            require_once ENGINE_DIR . '/mods/access_control.php';
            $isPermitted = checkAssess((int)$news["id"], "news");
            if (!$isPermitted) {
                unset($newsList[$key]);
                continue;
            }

            $news['category_alt_names'] = getCategoriesAltNames($news['id'], $moduleName);
            $categories = getCategoriesList($news['id'], $moduleName);

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

            if (!empty($news['full_desc'])) {
                $news['full_desc'] = html_entity_decode($news['full_desc'], ENT_QUOTES, 'UTF-8');
            }
        }

        $categoriesDataList = getModuleCategoriesDataList($moduleName);

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

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

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

        $smarty->assign('currentPage', $currentPage);
        $smarty->assign('categoriesDataList', $categoriesDataList);

        $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' => $newsList]));

        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }

    // Функция для подсчета общего количества новостей с фильтрацией по языку
    function countNews($lang_code) {
        global $db_connect;

        // Получаем количество новостей с фильтрацией по языку
        $count = $db_connect->count('news', [
            'language' => $lang_code
        ]);

        return $count;
    }
    
    $smarty->assign($config);