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

    use CoinbaseCommerce\ApiClient;
    use CoinbaseCommerce\Resources\Charge;

    const PAYMENT_METHOD_C = "coinbase";

    function viewPaymentControllerCoinbase(){
        global $db_connect, $ps_config, $user_id;
        if ($_POST["payment_method"] == PAYMENT_METHOD_C) {
            ApiClient::init($ps_config[PAYMENT_METHOD_C]["api_token"]);

            $discountData = calculateDiscount($_POST["promocode"] ?? "", $_POST["price"], $db_connect);
            $price = $discountData["finalAmount"];

            $chargeData = [
                'name' => 'Товар или услуга',
                'description' => 'Описание товара или услуги',
                'local_price' => [
                    'amount' => $price,
                    'currency' => $_POST["currency"]
                ],
                'pricing_type' => 'fixed_price',
                'metadata' => [
                    'customer_id' => $user_id,
                    'customer_name' => 'Иван Иванов'
                ],
                'redirect_url' => $ps_config[PAYMENT_METHOD_C]["successUrl"],
                'cancel_url' => $ps_config[PAYMENT_METHOD_C]["errorUrl"]
            ];

            ob_start();
            try {
                $charge = Charge::create($chargeData);
                $transactionId = $charge["id"];
                $status = 'pending';
                $action = !empty($_POST["action"]) && $_POST["action"] == "balance" ? $_POST["action"] : 'product_buy';
                $date = date("Y-m-d H:i:s");
                $description = '---';
                $paymentMethod = PAYMENT_METHOD_C;

                $requestFullInfo = getRequestUserFullInfo();

                insertTransaction($transactionId, [
                    "status" => $status,
                    "action" => $action,
                    "description" => $description,
                    "payment_method" => $paymentMethod,
                    "date" => $date,
                    "requestFullInfo" => $requestFullInfo,
                    "sum" => $price,
                    "fee" => null,
                ]);

                if (isset($_POST["deliveryCheckbox"]) && $_POST["deliveryCheckbox"] == "on") {
                    insertDelivery($transactionId, $_POST);
                }

                header("Location: " . $charge["hosted_url"]);
                exit;
            } catch (Exception $e) {
                ob_end_clean();
                echo 'Ошибка: ' . $e->getMessage();
            }

            if (isset($_GET['charge_id'])) {
                $charge_id = $_GET['charge_id'];
                try {
                    $charge = Charge::retrieve($charge_id);
                    echo "Статус платежа: " . $charge->status;
                } catch (Exception $e) {
                    echo 'Ошибка: ' . $e->getMessage();
                }
            }
        }
    }
    function errorControllerCoinbase() {
        global $smarty, $config, $ps_config;

        updateTransactionStatus("a1cc2bd4-3606-4e74-9d82-045625646c99", "canceled");

        $smarty->assign('title', 'Ошибка - Skills Engine');
        $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/products">Товары</a></li>
            <li class="breadcrumb-item active">Ошибка</li>
        ');

        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR."/".$config["skin"].'/payment/coinbase/error.tpl'));
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');
        exit;

    }
    function successControllerCoinbase() {
        global $db_connect, $smarty, $config, $ps_config;
        \Stripe\Stripe::setApiKey($ps_config["stripe"]["api_token"]);
        if ($_GET["session_id"]) {
            $session = \Stripe\Checkout\Session::retrieve($_GET["session_id"]);
            $query = $db_connect->prepare("SELECT * FROM `transactions` WHERE `transaction_id` = ?");
            $query->bind_param("s", $_GET["session_id"]);
            $query->execute();
            $result = $query->get_result();

            $data = $result->fetch_assoc();
            $intendID = $session->payment_intent;
            $paymentIntent = \Stripe\PaymentIntent::retrieve($intendID);

            $amount = $paymentIntent->amount / 100;
            $amount = number_format($amount, 2);
            $amount = str_replace(",", "", $amount);
            $currency = $paymentIntent->currency;
            $status = $paymentIntent->status;

            $updateQuery = $db_connect->prepare("UPDATE `transactions` SET `status` = ? WHERE `transaction_id` = ?");
            $updateQuery->bind_param("ss", $status, $_GET["session_id"]);
            $updateQuery->execute();
            $smarty->assign('amount', $amount);
            $smarty->assign('currency', $currency);
            $_SESSION["cart"] = [];

        }

        $smarty->assign('title', 'Ошибка - Skills Engine');
        $smarty->assign('page_name', '
            <li class="breadcrumb-item"><a href="/products">Товары</a></li>
            <li class="breadcrumb-item active">Ошибка</li>
        ');

        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR."/".$config["skin"].'/payment/coinbase/success.tpl'));
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');
        exit;
    }