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

    header('Content-Type: application/json');
    global $db_connect;
    $data = json_decode(file_get_contents('php://input'), true);

    // Проверяем авторизацию
    session_start();
    if(empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Вы не авторизованы']);
        exit;
    }

    $transactionId = $data['transaction_id'] ?? null;
    $reason = $data['reason'] ?? null;
    $userId = $_SESSION['user_id'];


    if(!$transactionId) {
        echo json_encode(['success' => false, 'message' => 'Нет ID транзакции']);
        exit;
    }

    // Проверяем, есть ли такая транзакция у пользователя
    $transaction = $db_connect->get('transactions', '*', [
        'transaction_id' => $transactionId,
        'user_id' => $userId
    ]);

    if(!$transaction) {
        echo json_encode(['success' => false, 'message' => 'Транзакция не найдена']);
        exit;
    }

    // Проверяем, нет ли уже запроса на возврат
    $existing = $db_connect->get('refund_requests', '*', ['transaction_id' => $transactionId]);
    if($existing) {
        echo json_encode(['success' => false, 'message' => 'Запрос уже отправлен']);
        exit;
    }

    // Создаём запрос
    try {
        $db_connect->insert('refund_requests', [
            'transaction_id' => (int)$transaction["id"],
            'user_id' => (int)$userId,
            'status' => 'pending',
            'reason' => $reason, // позже можно сделать форму с textarea для причины
        ]);
        echo json_encode(['success' => true]);

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $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);
}