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

    function deposit($currency, $amount, $otherUserID = null)
    {
        global $db_connect, $config, $user_id;
        $user_id = !empty($otherUserID) ? $otherUserID : $user_id;

        $userData = $db_connect->get("users", "*", ["id" => $user_id]);
        $finalBalance = "";
        if (!empty($userData["balance"]) || $userData["balance"] == 0) {
            $convertedBalance = $amount;

            $baseCurrency = $config['payment_info']['default_currency'];
            $currentRate = $config['payment_info']['currencies'][$baseCurrency] ?? null;
            $baseRate = $config['payment_info']['currencies'][strtoupper($currency)] ?? null;

            if ($currentRate === null || $baseRate === null) {
                die("Ошибка: отсутствуют данные о курсе валют.");
            }

            $convertedBalance = convertPrice($amount, $baseCurrency, strtoupper($currency), $baseRate, $currentRate);

            $finalBalance = (int)$convertedBalance + (int)$userData["balance"];

            $updateQuery = $db_connect->update("users", ["balance" => $finalBalance], ["id" => $user_id]);


            if (!$updateQuery) {
                die("Ошибка подготовки запроса: " . $db_connect->error);
            }
        }

        return $finalBalance;
    }

    function withdraw($withdrawableAmount, $currency)
    {
        global $db_connect, $user_id, $config;

        $userData = $db_connect->get("users", "*", ["id" => $user_id]);

        if (!$userData) {
            return ['success' => false, 'message' => 'Пользователь не найден.'];
        }

        $currentBalance = $userData['balance'];

        $withdrawableAmount = convertAmount($withdrawableAmount, strtoupper($currency), $config["payment_info"]["default_currency"]);

        if ((int)$withdrawableAmount > (int)$currentBalance) {
            return ['success' => false, 'message' => 'Недостаточно средств для вывода.'];
        }

        try {
            $newBalance = $currentBalance - $withdrawableAmount;

            $db_connect->update("users", ["balance" => $newBalance], ["id" => $user_id]);

            $uniquePart = strtoupper(uniqid($user_id));
            $transactionId = "MEGA-DIGITAL" . date("YmdHis") . $uniquePart;

            $requestFullInfo = getRequestUserFullInfo();

            insertTransaction($transactionId, [
                "date" => date("Y-m-d H:i:s"),
                "status" => "succeeded",
                "action" => "withdraw",
                "description" => "---",
                "sum" => $withdrawableAmount,
                "fee" => null,
                "requestFullInfo" => $requestFullInfo,
                "payment_method" => "mds-cms",
            ]);

            return ['success' => true, 'message' => 'Вывод успешно выполнен.', 'newBalance' => $newBalance, 'transactionId' => $transactionId];
        } catch (Exception $e) {

            return ['success' => false, 'message' => 'Произошла ошибка: ' . $e->getMessage()];
        }
    }


