<?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 allLotsController($lang_code) {
        global $db_connect, $smarty, $config, $lang;
    
        // Получаем номер текущей страницы
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
    
        // Рассчитываем с какой записи начать выборку
        $start = ($currentPage - 1) * $config['modules']['lots']['lots_per_page'];
    
        // Подготавливаем запрос для получения новостей с фильтрацией по языку и пагинацией
        $query = $db_connect->prepare("SELECT * FROM lots WHERE language = ? LIMIT ?, ?");
        $query->bind_param('sii', $lang_code, $start, $config['modules']['lots']['lots_per_page']);
        $query->execute();
        $result = $query->get_result();
    
        // Проверяем успешность выполнения запроса
        if (!$result) {
            die('Ошибка выполнения запроса (' . $db_connect->errno . ') ' . $db_connect->error);
        }
    
        // Получаем все лоты аукциона
        $lotsList = $result->fetch_all(MYSQLI_ASSOC);

        $currentCurrency = getCurrentCurrency();
        $baseCurrency = $config['payment_info']['default_currency'];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        $currentRate = $config['payment_info']['currencies'][$currentCurrency];
        foreach ($lotsList as &$lots) {
            $lots['converted_price'] = convertPrice($lots['start_price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);
        }
    
        // Для каждого лота получаем категории и их alt_name
        foreach ($lotsList as &$lots) {
            $categories = explode(',', $lots['category']);
            $altNames = [];
    
            // Получаем alt_name для каждой категории
            foreach ($categories as $category) {
                $category = trim($category);
                $altNameQuery = $db_connect->prepare('SELECT alt_name FROM lots_categories WHERE name = ?');
                $altNameQuery->bind_param('s', $category);
                $altNameQuery->execute();
                $altNameResult = $altNameQuery->get_result();
                $altName = $altNameResult->fetch_assoc();
                $altNames[] = $altName ? $altName['alt_name'] : '';
            }
            $lots['category_alt_names'] = implode(',', $altNames);
    
            // Декодируем описания лота аукциона
            if (!empty($lots['short_desc'])) {
                $lots['short_desc'] = html_entity_decode($lots['short_desc'], ENT_QUOTES, 'UTF-8');
            }
    
            if (!empty($lots['full_desc'])) {
                $lots['full_desc'] = html_entity_decode($lots['full_desc'], ENT_QUOTES, 'UTF-8');
            }
        }
        
        // Функция для подсчета общего числа товаров с учетом языка
        function countEvents($lang_code) {
            global $db_connect;
            // Подготавливаем запрос для подсчета объявлений с фильтрацией по языку
            $query = $db_connect->prepare('SELECT COUNT(*) as total FROM lots WHERE language = ?');
            $query->bind_param('s', $lang_code);
            $query->execute();
            $result = $query->get_result();
            $count = $result->fetch_assoc()['total'];
            return $count;
        }
        
        // Рассчитываем количество страниц для пагинации
        $totalPages = ceil(countEvents($lang_code) / $config['modules']['lots']['lots_per_page']);
        require_once(ENGINE_DIR . '/mods/pagination.php');
    
        // Передаем данные в Smarty
        $smarty->assign('title', $lang['module_name']['lots'] . ' - ' . $config['title']);
        $smarty->assign('page_name', '<li class="breadcrumb-item active">'. $lang['module_name']['lots'] . '</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/lots/' . $config['modules']['lots']['short_tpl'], ['lotsList' => $lotsList]));
    
        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }
    
    $smarty->assign($config);