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

        $categoryData = $db_connect->get("ads_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';
        $adsList = getFilterDataList("ads", $lang_code, null, [
            "n.price", "n.authority", "n.phone", "n.email"
        ], $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 ($adsList as &$ad) {
            $ad['converted_price'] = convertPrice($ad['price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);

            $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');
            }
        }
        $categoriesDataList = getModuleCategoriesDataList("ads");

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

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