<?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($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
    require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");
    define('ENGINE_DIR', $_SERVER['DOCUMENT_ROOT'] . '/engine');

    header('Content-Type: application/json');
    global $db_connect, $config;

    session_start();
    // Получаем данные из AJAX
    $data = json_decode(file_get_contents('php://input'), true);
    $id = $data['id'] ?? null;
    $action = $data['action'] ?? null;

    // Проверка входных данных
    if (!$id || !in_array($action, ['approve', 'reject'])) {
        echo json_encode(['success' => false, 'message' => 'Неверные данные']);
        exit;
    }

    // Выбираем статус
    $status = $action === 'approve' ? 'approved' : 'rejected';

    try {
        require_once ENGINE_DIR . '/mods/transaction.php';
        require_once ENGINE_DIR . '/mods/locationV2.php';

        $refundRequest = $db_connect->get("refund_requests", "*", ["id" => $id]);
        if (!$refundRequest) {
            throw new Exception("refund request not found");
        }

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

        $transaction = $db_connect->get("transactions", "*", ["id" => $refundRequest["transaction_id"]]);
        if (!$transaction) {
            throw new Exception("transaction not found");
        }

        if ($status === 'approved') {
            $refundData = refundStripeTransaction($transaction["transaction_id"]);

            $refund = $refundData["refund"];

            if ($refund->status === "succeeded") {

                if ($transaction["action"] === "balance") {
                    $currentBalance = $user['balance'];

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

                    $newBalance = $currentBalance - $withdrawableAmount;

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

                }
                $requestFullInfo = getRequestUserFullInfo();
                $_POST["currency"] = $transaction["currency"];

                insertTransaction($refund->id, [
                    "date" => date("Y-m-d H:i:s"),
                    "status" => $refund->status,
                    "action" => "refund",
                    "description" => "",
                    "sum" => $transaction["sum"],
                    "fee" => 0,
                    "requestFullInfo" => $requestFullInfo,
                    "payment_method" => "stripe", //todo: dynamic
                    'pdf_url' => $refundData["rUrl"],
                ], $user["id"]);

            }
        }

        $db_connect->update('refund_requests', ['status' => $status, "admin_id" => $_SESSION["id"]], ['id' => $id]);

        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }

    function refundStripeTransaction($transactionId, $amount = null) {
        require_once ENGINE_DIR."/payment/systems/general_config.php";
        global $db_connect;

        $transaction = $db_connect->get('transactions', '*', ['transaction_id' => $transactionId]);
        if (!$transaction) {
            throw new Exception("Транзакция не найдена");
        }

        $apiToken = $ps_config['stripe']["testMode"] ? $ps_config['stripe']["test_api_token"] : $ps_config['stripe']["api_token"];
        \Stripe\Stripe::setApiKey($apiToken);

        try {
            $refundData = ['payment_intent' => $transaction['transaction_id']];
            if ($amount !== null) {
                $refundData['amount'] = $amount * 100; // в центах
            }

            \Stripe\Stripe::setApiKey($apiToken);

            $session = \Stripe\Checkout\Session::retrieve($transactionId);
            $paymentIntentId = $session->payment_intent;


            $pi = \Stripe\PaymentIntent::retrieve($session->payment_intent);

            $charge = \Stripe\Charge::retrieve($pi->latest_charge);

            $rUrl = $charge->receipt_url;

            // теперь делаем возврат
            $refund = \Stripe\Refund::create([
                'payment_intent' => $paymentIntentId,
            ]);

            $db_connect->update('transactions', [
                'status' => $refund->status,
                'commission_fee' => $transaction['commission_fee'], // можно отдельно, если нужно
                'sum' => $amount ?? $transaction['sum'],
                'updated_at' => date("Y-m-d H:i:s"),
            ], ['transaction_id' => $transactionId]);

            return [
                "refund" => $refund,
                "rUrl" => $rUrl,
            ];

        } catch (\Stripe\Exception\ApiErrorException $e) {
            throw new Exception("Stripe error: " . $e->getMessage());
        }
    }


    function convertAmount($amount, $baseCurrency, $currentCurrency)
    {
        global $config;

        $currentRate = $config['payment_info']['currencies'][$currentCurrency];
        $baseRate = $config['payment_info']['currencies'][$baseCurrency];
        return convertPrice($amount, $baseCurrency, $currentCurrency, $baseRate, $currentRate);
    }

    function convertPrice($price, $baseCurrency, $currentCurrency, $baseRate, $currentRate) {
        $price = floatval($price);
        $baseRate = floatval($baseRate);
        $currentRate = floatval($currentRate);
        return round($price * ($currentRate / $baseRate), 2);
    }