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

        // Получаем номер текущей страницы
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
    
        // Рассчитываем с какой записи начать выборку
        $start = ($currentPage - 1) * $config['modules']['auctions']['auctions_per_page'];

        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $auctionsList = getFilterDataList("auctions", $lang_code, $start, [
            "n.title", "n.short_desc", "n.full_desc", "n.current_price", "n.buy_now_price"
        ], null, null, [
            "n.language", "n.image", "n.short_desc", "n.full_desc", "n.alt_name", "n.views"
        ]);

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

        // Для каждого лота получаем категории и их alt_name
        foreach ($auctionsList as $key => &$auctions) {
            $auctions["image"] = $db_connect->get("auction_images", "img_path", ["auction_id" => $auctions['id']]);

            require_once ENGINE_DIR . '/mods/access_control.php';
            $isPermitted = checkAssess((int)$auctions["id"], "auctions");
            if (!$isPermitted) {
                unset($auctionsList[$key]);
                continue;
            }

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

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

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

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