<?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 lotsByCategoryController($category, $lang_code) {
        global $db_connect, $smarty, $config, $lang;
        
        // Проверяем, существует ли категория
        $categoryQuery = $db_connect->prepare('SELECT * FROM lots_categories WHERE alt_name = ?');
        $categoryQuery->bind_param('s', $category);
        $categoryQuery->execute();
        $categoryResult = $categoryQuery->get_result();
        $categoryData = $categoryResult->fetch_assoc();
        $categoryQuery->close();
    
        if (!$categoryData) {
            // Категория не найдена, отображаем ошибку 404
            header("HTTP/1.0 404 Not Found");
            $smarty->assign('error_message', 'Категория не найдена');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
            exit;
        }
    
        // Получаем данные из базы данных
        $stmt = $db_connect->prepare('SELECT * FROM lots WHERE category LIKE ? AND language = ?');
        if (!$stmt) {
            die('Ошибка подготовки запроса (' . $db_connect->errno . ') ' . $db_connect->error);
        }
        $categorySearch = '%' . $categoryData['name'] . '%';
        $stmt->bind_param('ss', $categorySearch, $lang_code);
        $stmt->execute();
        if ($stmt->error) {
            die('Ошибка выполнения запроса (' . $stmt->errno . ') ' . $stmt->error);
        }
        $result = $stmt->get_result();
        $lotsList = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    
        // Обработка смены валюты
        $currentCurrency = getCurrentCurrency();
        $baseCurrency = $config['payment_info']['default_currency'];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        $currentRate = $config['payment_info']['currencies'][$currentCurrency];
        foreach ($lotsList as &$product) {
            $product['converted_price'] = convertPrice($product['start_price'], $baseCurrency, $currentCurrency, $baseRate, $currentRate);
        }
    
        // Получаем alt_names для каждой категории
        foreach ($lotsList as &$lots) {
            $categories = explode(',', $lots['category']);
            $altNames = [];
            foreach ($categories as $category) {
                $category = trim($category);
                $altNameQuery = $db_connect->prepare('SELECT alt_name FROM lots_categories WHERE name = ?');
                $altNameQuery->bind_param('s', $category);
                $altNameQuery->execute();
                $altNameResult = $altNameQuery->get_result();
                $altName = $altNameResult->fetch_assoc();
                $altNames[] = $altName ? $altName['alt_name'] : '';
            }
            $lots['category_alt_names'] = implode(',', $altNames);
    
            // Декодируем описания новости
            if (!empty($lots['short_desc'])) {
                $lots['short_desc'] = html_entity_decode($lots['short_desc'], ENT_QUOTES, 'UTF-8');
            }
        }
    
        // Рассчитываем количество страниц для пагинации относительно товаров с данной категорией
        $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $lotsPerPage = $config['modules']['lots']['lots_fromcats_per_page'];

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