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

        $categoryData = $db_connect->get("products_categories", "*", ["alt_name" => $category]);

        if (!$categoryData) {
            // Категория не найдена, отображаем ошибку 404
            header("HTTP/1.0 404 Not Found");
            $smarty->assign('error_message', 'Категория не найдена');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
            exit;
        }

        $categorySearch = '%' . $categoryData['name'] . '%';

        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $productsList = getFilterDataList("products", $lang_code, null, [
            "n.price"
        ], $categoryData["id"]);
        require_once ENGINE_DIR . '/mods/get_module_categories.php';

        // Обработка смены валюты
        $currentCurrency = getCurrentCurrency();
        $baseCurrency = $config['payment_info']['default_currency'];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        $currentRate = $config['payment_info']['currencies'][$currentCurrency];

        // Получаем alt_names для каждой категории
        foreach ($productsList as &$product) {
            $product['converted_price'] = convertPrice($product['price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);

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

            // Декодируем описания новости
            if (!empty($product['short_desc'])) {
                $product['short_desc'] = html_entity_decode($product['short_desc'], ENT_QUOTES, 'UTF-8');
            }
        }
        $categoriesDataList = getModuleCategoriesDataList("products");

        // Рассчитываем количество страниц для пагинации относительно товаров с данной категорией
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $productsPerPage = $config['modules']['products']['products_fromcats_per_page'];

        require_once(ENGINE_DIR . '/mods/pagination.php');
        $totalPages = ceil(count($productsList) / $productsPerPage);
    
        // Определяем, с какой новости начинать отображение на текущей странице
        $start = ($currentPage - 1) * $productsPerPage;
    
        // Передача данных в Smarty
        $smarty->assign('title', $lang['module_name']['products'] . ' - ' . $config['title']);
        $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/products">' . $lang['module_name']['products'] . '</a></li>
            <li class="breadcrumb-item active">' . $categoryData['name'] . '</li>
        ');
        $smarty->assign('currentPage', $currentPage);
        $smarty->assign('totalPages', $totalPages);
        $smarty->assign('pagination', generatePagination($currentPage, $totalPages));
        $smarty->assign('currentCurrency', $currentCurrency);
        $smarty->assign('productsList', array_slice($productsList, $start, $productsPerPage));
        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/modules/products/' . $config['modules']['products']['short_tpl'], ['productsList' => array_slice($productsList, $start, $productsPerPage), 'category_alt_names' => $categoryData['alt_name']]));
    
        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }
    $smarty->assign($config);