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

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

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

        require_once ENGINE_DIR . '/mods/module_condition_data.php';
        $shopProductsList = getFilterDataList("shop", $lang_code, $start, [
            "n.price",
            "n.slug",
            "n.name",
            "n.description",
            "n.shop_id"
        ], null, "shop_products", ["n.title", "n.image", "n.short_desc", "n.full_desc", "n.alt_name", "n.views"]);

        // Получаем текущую валюту и курс
        $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/access_control.php';
        require_once ENGINE_DIR . '/mods/get_module_categories.php';
        require_once ENGINE_DIR.'/mods/rating_control.php';

        foreach ($shopProductsList as $key => &$product) {
            // Конвертируем цену
            $product['converted_price'] = convertPrice($product['price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);

            // Проверка доступа
            $isPermitted = checkAssess((int)$product["id"], 'shop_products');
            if (!$isPermitted) {
                unset($shopProductsList[$key]);
                continue;
            }

            $product["image_url"] = $db_connect->get("shop_product_files", "url", ["product_id" => $product["id"]]) ?? [];
            $product["rating"] = getRating('product', $product["id"]);
            $product["shop"] = $db_connect->get("shops", "*", ["shop_id" => $product["shop_id"]]);


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

        function countShopProducts() {
            global $db_connect;
            return $db_connect->count("shop_products");
        }

        $totalPages = ceil(countShopProducts() / $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']);
       // $smarty->assign('page_name', '<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/shops/' . $config['modules']['shop']['short_tpl'], ['shopProducts' => $shopProductsList]));

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


    $smarty->assign($config);