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

        // Получаем текущую страницу из URL или устанавливаем её в 1, если отсутствует
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Рассчитываем начальную точку для запроса на основе пагинации
        $start = ($currentPage - 1) * $config['modules']['products']['products_per_page'];

        $moduleName = "products";

        // Обновляем запрос для получения товаров с учетом языка
        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $productsList = getFilterDataList($moduleName, $lang_code, $start, [
            "n.price"
        ]);

        // Получаем текущую валюту и курс
        $currentCurrency = getCurrentCurrency();
        $baseCurrency = $config['payment_info']['default_currency'];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        $currentRate = $config['payment_info']['currencies'][$currentCurrency];


        require_once ENGINE_DIR . '/mods/get_module_categories.php';
        // Получаем альтернативные имена категорий
        foreach ($productsList as $key => &$product) {
            $product['converted_price'] = convertPrice($product['price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);


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

            $product['category_alt_names'] = getCategoriesAltNames($product['id'], $moduleName);
            $categories = getCategoriesList($product['id'], $moduleName);

            if (!empty($product['short_desc'])) {
                $product['short_desc'] = html_entity_decode($product['short_desc'], ENT_QUOTES, 'UTF-8');
            }

            if (!empty($product['full_desc'])) {
                $product['full_desc'] = html_entity_decode($product['full_desc'], ENT_QUOTES, 'UTF-8');
            }
        }

        $categoriesDataList = getModuleCategoriesDataList($moduleName);

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

        // Рассчитываем количество страниц для пагинации
        $totalPages = ceil(countProducts($lang_code) / $config['modules']['products']['products_per_page']);
        require_once(ENGINE_DIR . '/mods/pagination.php');

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

        require_once(ENGINE_DIR . '/mods/binding_control.php');
        generateBindings($moduleName, '<li class="breadcrumb-item active">'. $lang['module_name']['products'] . '</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/products/' . $config['modules']['products']['short_tpl'], ['productsList' => $productsList]));

        require_once(ENGINE_DIR . '/mods/offline.php');
    }

    $smarty->assign($config);