<?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");

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

    $user = $db_connect->get("users", "*", ["email" => $_SESSION["user_email"] ?? null]);

    if (!$user) {
        // Пользователь не найден
        $smarty->assign('error_message', 'Пользователь не найден');
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
    } else {

        $smarty->assign('title', 'Мой баланс - '.$config["title"]);
        $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" => ["created_at" => "DESC"]
            ]
        ) ?? [];

        $userBonusBalance = $db_connect->get("user_bonus_balance", "balance", [
            "user_id" => $_SESSION["user_id"],
        ]) ?? 0;

        $balanceHolds = $db_connect->sum("balance_holds", "amount", [
            "user_id" => $user_id,
            "status" => "hold"
        ]);

        $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);

        $transactionHistoryParsed = [];
        foreach ($transactionHistory as $key => &$transaction) {

            if (!empty($transaction["pdf_url"])) {
                $transactionHistoryParsed[$key]["pdf_url"] = "<a target='_blank' href='{$transaction["pdf_url"]}'>Чек {$transaction['payment_method']}</a>" ?? "";
            } else {
                $transactionHistoryParsed[$key]["pdf_url"] = "Без чека";
            }

            $transactionHistoryParsed[$key][$lang["widgets"]["date"]] = $transaction["created_at"];
            if (!empty($transaction["action"])) {
                if (str_contains($transaction["action"], "dynamic")) {
                    $transaction["action"] = "dynamic";
                }

                switch ($transaction["action"]) {
                    case "product_buy":
                        $transactionHistoryParsed[$key][$lang["widgets"]["operation"]] = $lang["widgets"]["product_buy"];
                        break;

                    case "balance":
                        $transactionHistoryParsed[$key][$lang["widgets"]["operation"]] = $lang["widgets"]["balance"];
                        break;

                    case "withdraw":
                        $transactionHistoryParsed[$key][$lang["widgets"]["operation"]] = $lang["widgets"]["withdraw"];
                        break;

                    case "dynamic":
                        $transactionHistoryParsed[$key][$lang["widgets"]["operation"]] = $lang["widgets"]["dynamic"];
                        break;

                    case "refund":
                        $transactionHistoryParsed[$key][$lang["widgets"]["operation"]] = $lang["widgets"]["refund"];
                        break;
                }
            }

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

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

                    case "EUR";
                        $transaction["currency"] = "€";
                        break;
                }
            }
            $transactionHistoryParsed[$key][$lang["widgets"]["payment_method"]] = $transaction["payment_method"];
            $transactionHistoryParsed[$key][$lang["widgets"]["sum"]] = $transaction["sum"] . " " . $transaction["currency"];

            // -------- Добавляем кнопку возврата --------
            // проверяем, есть ли уже запрос на возврат
            $refund = $db_connect->get('refund_requests', '*', ['transaction_id' => $transaction['id']]);

            if (!$refund && $transaction["action"] != "refund" && $transaction["status"] != "pending" && $transaction["status"] != "canceled" && $transaction["payment_method"] == "stripe") {
                $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<a class='request-refund-btn' 
                             data-transaction-id='{$transaction['transaction_id']}'>Запросить возврат</a>";
            } else if ($transaction["action"] == "refund") {
                $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<span class='text-muted'></span>";
            } else if ($transaction["status"] == "pending") {
                $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<span class='text-muted'></span>";
            } else if ($transaction["status"] == "canceled") {
                $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<span class='text-muted'></span>";
            } else {
                switch ($refund['status']) {
                    case 'pending':
                        $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<span class='text-muted'>Запрос в обработке</span>";
                        break;
                    case 'approved':
                        $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<span class='text-success'>Возврат одобрен</span>";
                        break;
                    case 'rejected':
                        $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<span class='text-danger'>Возврат отклонён</span>";
                        break;
                }
            }

            if ($transaction["payment_method"] != "stripe") {
                $transactionHistoryParsed[$key][$lang["datatable"]["actions"]] = "<span class='text-muted'></span>";
            }

            if (!empty($transaction["status"])) {
                switch ($transaction["status"]) {
                    case "succeeded";
                        $transaction["status"] = "<p class=' {$transaction["status"]}'>{$lang["widgets"]["succeeded"]}</p>";
                        break;

                    case "pending";
                        $transaction["status"] = "<p class=' {$transaction["status"]}'>{$lang["widgets"]["pending"]}</p>";
                        break;

                    case "error";
                        $transaction["status"] = "<p class=' {$transaction["status"]}'>{$lang["widgets"]["error"]}</p>";
                        break;

                    case "canceled";
                        $transaction["status"] = "<p class=' {$transaction["status"]}'>{$lang["widgets"]["canceled"]}</p>";
                        break;
                    case "refunded";
                        $transaction["status"] = "<p class=' {$transaction["status"]}'>{$lang["widgets"]["refunded"]}</p>";
                        break;
                }

            }

            $transactionHistoryParsed[$key][$lang["widgets"]["status"]] = $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);
        });

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

        $smarty->assign('paymentBonuses', $paymentBonuses);
        $smarty->assign('action', "balance");
        $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('userBonusBalance', $userBonusBalance);
        $smarty->assign('balanceHolds', $balanceHolds);

        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/'.$config["skin"].'/my-wallet.tpl'));
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');

        exit;

    }

}