<?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 allAdsController($lang_code) {
        global $db_connect, $smarty, $config, $lang;
    
        // Получаем текущую страницу из URL или устанавливаем ее в 1, если отсутствует
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
    
        // Рассчитываем начальную точку для запроса на основе пагинации
        $start = ($currentPage - 1) * $config['modules']['ads']['ads_per_page'];

        $moduleName = "ads";

        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $adsList = getFilterDataList($moduleName, $lang_code, $start, [
            "n.price", "n.authority", "n.phone", "n.email"
        ]);

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

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

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


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

            return $count;
        }
        
        // Рассчитываем количество страниц для пагинации
        $totalPages = ceil(countAds($lang_code) / $config['modules']['ads']['ads_per_page']);
        require_once(ENGINE_DIR . '/mods/pagination.php');
    
        // Передаем данные в Smarty
        $smarty->assign('categoriesDataList', $categoriesDataList);
        $smarty->assign('title', $lang['module_name']['ads'] . ' - ' . $config['title']);
        $smarty->assign('page_name', '');

        require_once(ENGINE_DIR . '/mods/binding_control.php');
        generateBindings($moduleName, '<li class="breadcrumb-item active">'. $lang['module_name']['ads'] . '</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/ads/' . $config['modules']['ads']['short_tpl'], ['adsList' => $adsList]));
    
        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }
    
    $smarty->assign($config);