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


$user_id = $user["id"];
$yourData = array('title' => 'Мой баланс - Skills Engine');
$smarty->assign('data', $yourData);
$smarty->assign('page_name', '
        <li class="breadcrumb-item active"><a href="/products">Мой баланс</a></li>
    ');

$userBalanceInfo = getConvertedBalanceInfo();

$transactionHistory = $db_connect->select("transactions", "*", ["user_id" => $user_id, "ORDER" => ["id" => "DESC"]]) ?? [];

$perPage = 5;
$totalTransactions = count($transactionHistory);
$totalPages = ceil($totalTransactions / $perPage);
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$currentPage = max(1, min($currentPage, $totalPages)); // Убедитесь, что страница корректна

$startIndex = ($currentPage - 1) * $perPage;
$paginatedTransactions = array_slice($transactionHistory, $startIndex, $perPage);
foreach ($paginatedTransactions as &$transaction) {
    //$transaction["sum"] = convertAmount($transaction["sum"], "RUB", getCurrentCurrency());
}

$transactionHistoryParsed = [];
foreach ($transactionHistory as $key => &$transaction) {
    $transactionHistoryParsed[$key]["Дата"] = $transaction["date"];
    if (!empty($transaction["action"])) {
        $transaction["action"] = str_contains($transaction["action"], "dynamic") ? "dynamic" : $transaction["action"];

        switch ($transaction["action"]) {
            case "product_buy";
            $transactionHistoryParsed[$key]["Операция"] = "Покупка продукта";

            case "balance";
            $transactionHistoryParsed[$key]["Операция"] = "Баланс";

            case "withdraw";
            $transactionHistoryParsed[$key]["Операция"] = "Вывод";

            case "dynamic";
            $transactionHistoryParsed[$key]["Операция"] = "Оплата";
        }
    }

    if (!empty($transaction["currency"])) {
        switch ($transaction["currency"]) {
            case "USD";
                $transaction["currency"] = "$";
                break;

            case "RUB";
                $transaction["currency"] = "₽";
                break;

            case "EUR";
                $transaction["currency"] = "€";
                break;
        }
    }

    if (!empty($transaction["status"])) {
        switch ($transaction["status"]) {
            case "succeeded";
                $transaction["status"] = "<p class='status {$transaction["status"]}'>Успешно</p>";
                break;

            case "pending";
                $transaction["status"] = "<p class='status {$transaction["status"]}'>В обработке</p>";
                break;

            case "error";
                $transaction["status"] = "<p class='status {$transaction["status"]}'>Ошибка</p>";
                break;

            case "canceled";
                $transaction["status"] = "<p class='status {$transaction["status"]}'>Отменено</p>";
        }

    }

    $transactionHistoryParsed[$key]["Система"] = $transaction["payment_method"];
    $transactionHistoryParsed[$key]["Сумма"] = $transaction["sum"] . " " . $transaction["currency"];
    $transactionHistoryParsed[$key]["Статус"] = $transaction["status"];


}

$dolarAmount = 0;
$euroAmount = 0;
$rubleAmount = 0;
if (getCurrentCurrency() == "RUB") {
    $dolarAmount = convertAmount($userBalanceInfo["finalBalance"], "RUB", "USD");
} elseif (getCurrentCurrency() == "USD") {
    $euroAmount = convertAmount($userBalanceInfo["finalBalance"], "USD", "EUR");
} elseif (getCurrentCurrency() == "EUR") {
    $dolarAmount = convertAmount($userBalanceInfo["finalBalance"], "EUR", "USD");
} else {
    $dolarAmount = convertAmount($userBalanceInfo["finalBalance"], getCurrentCurrency(), "USD");
}

$smarty->registerPlugin('modifier', 'json_encode', function($value) {
    return json_encode($value);
});
$smarty->assign('total_pages', $totalPages);
$smarty->assign('current_page', $currentPage);
$smarty->assign('transaction_history', $transactionHistoryParsed);
$smarty->assign('payment_configs', $ps_config);
$smarty->assign('currency', $userBalanceInfo["currentCurrency"]);
$smarty->assign('balance', $userBalanceInfo["finalBalance"]);
$smarty->assign('dolarAmount', $dolarAmount);
$smarty->assign('euroAmount', $euroAmount);

$smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/main/my-wallet.tpl'));

