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

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

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

        $moduletype = $db_connect->get('products', '*', [
            'alt_name' => $moduletype,
            'language' => $lang_code
        ]);

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

        // Получаем значения динамических полей для товаров
        require_once(ENGINE_DIR . '/mods/extra_fields.php');
        $productsFields = getDynamicFieldValues($db_connect, $moduletype['id'], 'products');
    
        // Подготовка данных о динамических полях для Smarty
        $smarty->assign('x_value', $productsFields['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 для данного товара
            // Получаем значения динамических полей для новости
            $moduleName = "products";

            require_once ENGINE_DIR . '/mods/get_module_categories.php';
            $moduletype['category_alt_names'] = getCategoriesAltNames($moduletype['id'], $moduleName);
            $categories = getCategoriesList($moduletype['id'], $moduleName);

            // Получаем и строим дерево комментариев
            $comments = fetch_comments($moduletype['id'], 'products');
            $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['price'], $baseCurrency, getCurrentCurrency(), $baseRate, $currentRate);

            // Устанавливаем массив переменных в Smarty
            $smarty->assign('title', $moduletype['title']  . ' - ' . $lang['module_name']['products'] . ' - ' . $config['title']);

            require_once(ENGINE_DIR . '/mods/binding_control.php');
            generateBindings($moduleName, '
                <li class="breadcrumb-item"><a href="/products">' . $lang['module_name']['products'] . '</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('products', $moduletype);
            $smarty->assign('comments', $moduletype_comments);
            $smarty->assign('entity', ['id' => $moduletype['id']]);
            $smarty->assign('entity_type', $moduletype);

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

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