<?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/libs/vendor/autoload.php';
    // Подключаем конфиг платежных систем
    require_once ENGINE_DIR.'/payment/systems/general_config.php';

    $user_id = $user['id'] ?? 0;

    if (isset($_POST["payment_method"]) && $_POST["payment_method"] == "stripe" || isset($_POST["method"]) && $_GET["method"] == "stripe") {
        require_once(ENGINE_DIR.'/payment/systems/stripe/payment.php'); 
    } else if (isset($_POST["payment_method"]) && $_POST["payment_method"] == "coinbase" || isset($_POST["method"]) && $_GET["method"] == "coinbase"){
        require_once(ENGINE_DIR.'/payment/systems/coinbase/payment.php'); 
    } else if (isset($_POST["payment_method"]) && $_POST["payment_method"] == "balance" || isset($_POST["method"]) && $_GET["method"] == "balance"){
        require_once(ENGINE_DIR.'/payment/systems/balance/payment.php');
    }

    function viewPaymentPage(){
        global $db_connect, $smarty, $config, $ps_config, $lang, $currency;

        $deliveryData = getDeliveryByUserId();

        $status = "";
        if (!empty($_GET["status"]) && $_GET["status"] == "error") {
            $status = "error";
        } else {
            $status = $_GET["status"] ?? "";
        }

        $action = "product_buy";
        if (isset($_GET["widget"])) {
            $widgetObj = $db_connect->get("payment_widgets", "*", ["id" => (int)$_GET["widget"]]);
            $widgetObj["pay_with_redirect"] = 0;

            if ($_GET["price"] == 0) {
                $widgetObj["disable_sum_input"] = 0;
            } else {
                $widgetObj["disable_sum_input"] = 1;
            }

            $widgetObj["settings"] = json_decode($widgetObj["settings"], true);
            $subscription = $db_connect->get("subscriptions", "*", ["widget_id" => $widgetObj["id"]]);

            $discountPercent = !empty($config["payment_info"]["default_discount_percent"]) ? $config['payment_info']['default_discount_percent'] : $subscription["discount_percent"] ?? "";
            $discountSum = !empty($config["payment_info"]["default_discount_sum"]) ? $config['payment_info']['default_discount_sum'] : $subscription["discount_sum"] ?? "";

            $discountedPrice = null;
            if (!empty($discountPercent) && $discountPercent > 1) {
                $discountedPrice = round($_GET["price"] - ($_GET["price"] * ($discountPercent / 100)));
            } else if (!empty($discountSum) && $discountSum > 1) {
                $discountedPrice = $_GET["price"] - convertAmount($discountSum, $config["payment_info"]["default_currency"], getCurrentCurrency());
            }

            $smarty->assign('discountedPrice', $discountedPrice);
            $smarty->assign('widgetObj', $widgetObj);
            $smarty->assign('widgetId', $widgetObj["id"]);
            $action = "dynamic";
        }

        $productParsedList = [];
        $allPrice = 0;
        if ($action == "product_buy") {
            $productList = $_SESSION["cart"];
            foreach ($productList as $id => $product) {
                if ($product["type"] == "shop_product") {
                    $productA = $db_connect->get("shop_products", "*", ["id" => $id]);
                } else {
                    $productA = $db_connect->get("products", "*", ["id" => $id]);
                }
                $productA["stored_quantity"] = $product["quantity"];
                $productParsedList[] = $productA;

                $allPrice += (int)$productA["price"] * $product["quantity"];
            }
        }

        $paymentBonuses = $db_connect->select("payment_bonuses", "*");
        $smarty->assign('paymentBonuses', $paymentBonuses);

        $smarty->assign("status", $status);
        $smarty->assign("productParsedList", $productParsedList);

        $smarty->assign('title', 'Выбор способа оплаты - Skills Engine');
        $smarty->assign('page_name', '
            <li class="breadcrumb-item active">Выбор способа оплаты</li>
        ');
        $smarty->assign('action', $action);
        $smarty->assign('deliveryData', $deliveryData);
        $smarty->assign('price', convertAmount($allPrice, $config["payment_info"]["default_currency"], getCurrentCurrency()));
        $smarty->assign('currency', $config["payment_info"]["default_currency"]);
        $smarty->assign('payment_configs', $ps_config);
        // Передаем данные в Smarty
        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR."/".$config["skin"].'/payment/payment.tpl'));
    
        // Передаем данные в Smarty
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');
        exit;
    }