<?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');

    // Устанавливаем функционал комментариев
    require_once(ENGINE_DIR . '/mods/comments.php');

    function lotController($moduletype, $lang_code) {
        global $db_connect, $smarty, $config, $lang;
        // Получаем данные из базы данных
        $stmt = $db_connect->prepare('SELECT * FROM lots WHERE alt_name = ? AND language = ?');
        $stmt->bind_param('ss', $moduletype, $lang_code);
        $stmt->execute();
        $result = $stmt->get_result();
        $moduletype = $result->fetch_assoc();
        $stmt->close();

        if (!$moduletype) {
            // Если аукцион не найден, показываем ошибку
            $smarty->assign('error_message', 'Аукцион не найден');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
            return; // Завершаем выполнение функции
        }

        // Получаем значения динамических полей для аукциона
        require_once(ENGINE_DIR . '/mods/extra_fields.php');
        $lotsFields = getDynamicFieldValues($db_connect, $moduletype['id'], 'lots');
    
        // Подготовка данных о динамических полях для Smarty
        $smarty->assign('x_value', $lotsFields['x_value'] ?? "");

        if ($moduletype) {
            $moduletype['short_desc'] = html_entity_decode($moduletype['short_desc'], ENT_QUOTES, 'UTF-8');
            $moduletype['full_desc'] = html_entity_decode($moduletype['full_desc'], ENT_QUOTES, 'UTF-8');
            // Получаем категории и их alt_name для данного аукциона
            $categories = explode(',', $moduletype['category']);
            $altNames = [];
            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'] : '';
            }
            $moduletype['category_alt_names'] = implode(',', $altNames);
            
            // Получаем и строим дерево комментариев
            $comments = fetch_comments($moduletype['id'], 'lots');
            $moduletype_comments = build_comment_tree($comments);

            $currentCurrency = getCurrentCurrency();
            $baseCurrency = $config['payment_info']['default_currency'];
            $currentRate = $config['payment_info']['currencies'][getCurrentCurrency()];
            $baseRate = $config['payment_info']['currencies'][$baseCurrency];
            $moduletype['converted_price'] = convertPrice($moduletype['start_price'], $baseCurrency, getCurrentCurrency(), $baseRate, $currentRate);

            // Получаем список участников
            $sql = "SELECT * FROM lots_participants ORDER BY registration_date DESC";
            $participantslist = $db_connect->query($sql);

            // Проверка наличия данных
            $lots_participants = array();
            while ($participants = $participantslist->fetch_assoc()) {
                // Добавляем каждого участника в массив
                $lots_participants[] = $participants;
            }

            // Фильтруем участников с подтвержденным статусом
            $confirmed_participants = array_filter($lots_participants, function($participant) {
                return $participant['status'] === 'confirmed';
            });

            $smarty->assign('confirmed_participants', $confirmed_participants);

            $moduleName = "lots";
            require_once(ENGINE_DIR . '/mods/widget-select.php');
            $smarty->assign('dynamicName', $moduletype["title"]);

            // Устанавливаем массив переменных в Smarty
            $smarty->assign('title', $moduletype['title']  . ' - ' . $lang['module_name']['lots'] . ' - ' . $config['title']);
            $smarty->assign('page_name', '
                <li class="breadcrumb-item"><a href="/lots">' . $lang['module_name']['lots'] . '</a></li>
                <li class="breadcrumb-item active">' . $moduletype['title'] . '</li>
            ');
            $smarty->assign('category_alt_names', $moduletype['category_alt_names']);
            $smarty->assign('categories', $categories);
            $smarty->assign('keywords', $moduletype['meta_keys']);
            $smarty->assign('description', $moduletype['meta_desc']);
            $smarty->assign('lots', $moduletype);
            $smarty->assign('comments', $moduletype_comments);
            $smarty->assign('entity', ['id' => $moduletype['id']]);
            $smarty->assign('entity_type', 'lots');

            $smarty->assign('currentCurrency', $currentCurrency);
            $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/modules/lots/' . $config['modules']['lots']['full_tpl'], ['lots' => $moduletype]));
            
            // Проверяем, выключен ли сайт
            require_once(ENGINE_DIR . '/mods/offline.php');
        }

        // Устанавливаем счетчик просмотров
        $sqltablename = 'lots';
        require_once(ENGINE_DIR . '/mods/views.php');
    }

    $smarty->assign($config);