<?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.'/payment/systems/general_config.php';
    require_once ENGINE_DIR.'/mods/delivery.php';

    function addToCartController(){
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
            $product_id = $_POST['product_id'];
            $quantity = $_POST['quantity'];
            // Проверка, существует ли корзина в сессии
            if (!isset($_SESSION['cart'])) {
                $_SESSION['cart'] = [];
            }
            // Добавление товара в корзину
            if (isset($_SESSION['cart'][$product_id])) {
                $_SESSION['cart'][$product_id]['quantity'] += $quantity;
            } else {
                $_SESSION['cart'][$product_id] = ['quantity' => $quantity];
            }

            $_SESSION['cart'][$product_id]["type"] = $_POST['type'] ?? "products";

            $cartAllQuantity = 0;
            foreach ($_SESSION['cart'] as $key => $value) {
                $cartAllQuantity += (int)$value['quantity'] ?? 0;
            }

            echo json_encode(['success' => true, "productCount" => $cartAllQuantity]);exit();
        }
    }
    function viewCartController(){
        global $db_connect, $smarty, $config, $ps_config;
        $currentCurrency = getCurrentCurrency();
        $baseCurrency = $config['payment_info']['default_currency'];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        $currentRate = $config['payment_info']['currencies'][$currentCurrency];
    
        // Получаем дополнительные данные о товарах из базы данных
        $productDetails = getProductDetails($_SESSION['cart'] ?? [], $baseCurrency, $currentCurrency, $baseRate, $currentRate);
    
        // Вычисляем общую сумму
        $totalPrice = calculateTotalPrice($productDetails);
    
        // Вычисляем общее количество товаров
        $cartCount = calculateCartCount($_SESSION['cart'] ?? []);

        $selectedPaymentMethod = "";
        $count = 0;
        foreach($ps_config as $paymentMethod => $configAssoc) {
            if ($configAssoc["enabled"] == true) {
                $count++;
                $selectedPaymentMethod = $paymentMethod;
            }
        }   
        
        if (!$count) {
            $smarty->assign('error_message', 'Нет активных платежных систем');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
        
        }

        $deliveryData = getDeliveryByUserId();

        // Передача данных корзины и общей суммы в Smarty
        $smarty->assign('cartContent', $productDetails);
        $smarty->assign('totalPrice', $totalPrice);
        $smarty->assign('currentCurrency', $currentCurrency);
        $smarty->assign('methodsCount', $count);
        $smarty->assign('selectedPaymentMethod', $selectedPaymentMethod);
        $smarty->assign('deliveryData', $deliveryData);

        // Устанавливаем массив переменных в Smarty
        $smarty->assign('title', 'Корзина - Skills Engine');
        $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/products">Товары</a></li>
            <li class="breadcrumb-item active">Корзина</li>
        ');
    
        // Передаем данные в Smarty
        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR."/".$config["skin"].'/payment/cart.tpl'));
    
        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }
    // Вспомогательная функция для получения дополнительных данных о товарах
    function getProductDetails($cartContent, $baseCurrency, $currentCurrency, $baseRate, $currentRate){
        global $db_connect;
        $productDetails = [];

        foreach ($cartContent as $product_id => $item) {
            $conditions = [
                'id' => $product_id
            ];

            // Запрос к базе данных с использованием универсальной функции select
            $product = $db_connect->get("products", "*", $conditions);
            $shopProduct = $db_connect->get("shop_products", "*", $conditions);

            if ($product) {
                $product['converted_price'] = convertPrice(
                    $product['price'],
                    $baseCurrency,
                    $currentCurrency,
                    $baseRate,
                    $currentRate
                );

                $productDetails[$product_id] = $product + ['quantity' => $item['quantity']];
            }

            if ($shopProduct) {
                $shopProduct['converted_price'] = convertPrice(
                    $shopProduct['price'],
                    $baseCurrency,
                    $currentCurrency,
                    $baseRate,
                    $currentRate
                );

                $shopProduct["title"] = $shopProduct['name'];

                $productDetails[$product_id] = $shopProduct + ['quantity' => $item['quantity']];
            }
        }

        return $productDetails;
    }
    // Вспомогательная функция для вычисления общей суммы
    function calculateTotalPrice($productDetails){
        $totalPrice = 0;
        foreach ($productDetails as $item) {
            $totalPrice += $item['converted_price'] * $item['quantity'];
        }
        return $totalPrice;
    }
    $smarty->assign($config);