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

        require_once ENGINE_DIR.'/mods/banned_words_detector.php';

        if (!checkIsAccessComment()) {
            $smarty->assign("commentingBlocked", true);
        }

        // Получаем аукцион
        $auction = $db_connect->get('auctions', '*', [
            'id' => $id,
            //'language' => $lang_code
        ]);

        $auction["image"] = $db_connect->get("auction_images", "img_path", ["auction_id" => $id]);

        if (!$auction) {
            $smarty->assign('error_message', 'Аукцион не найден');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
            return;
        }

        // Динамические поля
        require_once ENGINE_DIR . '/mods/extra_fields.php';
        $auctionFields = getDynamicFieldValues($db_connect, $auction['id'], 'auctions');
        $smarty->assign('x_value', $auctionFields['x_value'] ?? '');

        // Декод описаний
        $auction['short_desc'] = html_entity_decode($auction['short_desc'], ENT_QUOTES, 'UTF-8');
        $auction['full_desc']  = html_entity_decode($auction['full_desc'], ENT_QUOTES, 'UTF-8');

        $moduleName = 'auctions';

        // Категории
        require_once ENGINE_DIR . '/mods/get_module_categories.php';
        $auction['category_alt_names'] = getCategoriesAltNames($auction['id'], $moduleName);
        $categories = getCategoriesList($auction['id'], $moduleName);

        // Комментарии
        $comments = fetch_comments($auction['id'], 'auctions');
        $auction_comments = build_comment_tree($comments);

        // Валюта
        $currentCurrency = getCurrentCurrency();
        $baseCurrency    = $config['payment_info']['default_currency'];
        $currentRate     = $config['payment_info']['currencies'][$currentCurrency];
        $baseRate        = $config['payment_info']['currencies'][$baseCurrency];

        $auction['converted_price'] = convertPrice(
            $auction['start_price'],
            $baseCurrency,
            $currentCurrency,
            $baseRate,
            $currentRate
        );

        // Участники
        $participants = $db_connect->select('auctions_participants', '*', [
            'auctions_title' => $auction['title']
        ]);

        $confirmed_participants = array_filter($participants ?? [], function ($p) {
            return $p['status'] === 'confirmed';
        });

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

        // Виджеты
        require_once ENGINE_DIR . '/mods/widget-select.php';
        $smarty->assign('dynamicName', $auction['title']);

        require_once(ENGINE_DIR . '/mods/binding_control.php');
        generateBindings("auctions", '
                <li class="breadcrumb-item"><a href="/auctions">Аукционы</a></li>
                <li class="breadcrumb-item active">' . $auction['title'] . '</li>
            ');
        // Smarty assign
        $smarty->assign([
            'title'       => $auction['title'].' - '.$lang['module_name']['auctions'].' - '.$config['title'],

            'keywords'    => $auction['meta_keys'],
            'description' => $auction['meta_desc'],
            'categories'  => $categories,
            'category_alt_names' => $auction['category_alt_names'],
            'auctions'    => $auction,

            'currentCurrency' => $currentCurrency,
            'content'     => $smarty->fetch(
                TEMPLATES_DIR.'/'.$config['skin'].'/modules/auctions/'.$config['modules']['auctions']['full_tpl'],
                ['auctions' => $auction, 'entity'      => ['id' => $auction['id']],
                    'entity_type' => 'auctions',             'comments'    => $auction_comments,
                ]
            )
        ]);

        // Offline check
        require_once ENGINE_DIR . '/mods/offline.php';

        // Счётчик просмотров
        $sqltablename = 'auctions';
        require_once ENGINE_DIR . '/mods/views.php';
    }

    $smarty->assign($config);