<?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."/mods/locationV2.php");
    require_once(ENGINE_DIR."/mods/promocode_checker.php");
    require_once(ENGINE_DIR."/mods/user_balance.php");
    require_once(ENGINE_DIR."/mods/convert_user_balance.php");
    require_once(ENGINE_DIR."/mods/transaction.php");
    require_once(ENGINE_DIR."/mods/delivery.php");

    const PAYMENT_METHOD_B = 'balance';

    function viewPaymentControllerBalance(){
        global $db_connect, $ps_config, $user_id, $smarty, $config;

        if ($_POST["payment_method"] == PAYMENT_METHOD_B) {
            $paymentMethod = PAYMENT_METHOD_B;

            $sum = convertAmount($_POST["price"], $_POST["currency"],$config["payment_info"]["default_currency"]);

            $discountData = calculateDiscount($_POST["promocode"] ?? "", $sum, $db_connect);
            $sum = $discountData["finalAmount"];

            $uniquePart = strtoupper(uniqid($user_id));
            $transactionId = $config["title"] . date("YmdHis") . $uniquePart;

            $requestFullInfo = getRequestUserFullInfo();

            $date = date("Y-m-d H:i:s");
            $status = 'pending';
            $action = !empty($_POST["action"]) && $_POST["action"] == "balance" ? $_POST["action"] : 'product_buy';
            $description = '---';
            $fee = null;

            insertTransaction($transactionId, [
                "date" => $date,
                "status" => $status,
                "action" => $action,
                "description" => $description,
                "sum" => $sum,
                "fee" => $fee,
                "requestFullInfo" => $requestFullInfo,
                "payment_method" => $paymentMethod,
            ]);

            $withdraw = withdraw($sum, $config["payment_info"]["default_currency"]);
            $balanceInfo = getConvertedBalanceInfo();

            $smarty->assign('user_balance', $balanceInfo["finalBalance"]);
            $smarty->assign('currency', strtolower(getCurrentCurrency()));

            $sum = convertAmount($sum, $config["payment_info"]["default_currency"], getCurrentCurrency());
            $smarty->assign('amount', $sum);
            if (!$withdraw["success"]) {
                updateTransactionStatus($transactionId, "error");

                $smarty->assign('title', 'Недостаточно средств - '.$config["title"]);

                $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/?myWallet">Товары</a></li>
            <li class="breadcrumb-item active">Ошибка</li>
             ');

                $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR."/".$config["skin"].'/payment/balance/error.tpl'));
            } else {
                updateTransactionStatus($transactionId, "succeeded");

                if (isset($_POST["deliveryCheckbox"]) && $_POST["deliveryCheckbox"] == "on") {
                    insertDelivery($transactionId, $_POST);
                }
                $_SESSION["cart"] = [];

                $smarty->assign('title', 'Успешная оплата - '.$config["title"]);

                $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/?myWallet">Товары</a></li>
            <li class="breadcrumb-item active">Успешно</li>
         '  );

                $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR."/".$config["skin"].'/payment/balance/success.tpl'));
            }

            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');
            exit;

        }

    }





