<?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/promocode_checker.php");
    require_once(ENGINE_DIR."/mods/user_balance.php");
    require_once(ENGINE_DIR."/mods/convert_user_balance.php");
    require_once(ENGINE_DIR."/mods/transaction.php");
    require_once(ENGINE_DIR."/data/countries-adjust-amount.php");


    const PAYMENT_METHOD = 'stripe';

    function viewPaymentControllerStripe(){
        global $db_connect, $ps_config, $smarty, $config, $dispatcher;
        if ($_POST["payment_method"] == PAYMENT_METHOD) {
            $paymentMethod = PAYMENT_METHOD;
            $apiToken = $ps_config[PAYMENT_METHOD]["testMode"] ? $ps_config[PAYMENT_METHOD]["test_api_token"] : $ps_config[PAYMENT_METHOD]["api_token"];

            $sum = 0;
            if (!empty($_POST["email"])) {
                $_SESSION["payment_email"] = $_POST["email"];
            }

            $session = createStripeSession($apiToken, $sum, $ps_config, $_POST["action"], $_POST["promocode"] ?? "");
            if ($session === null) {
                $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/stripe/error.tpl'));
                $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');
                exit;
            }
            $action = $_POST["action"];
            $requestFullInfo = getRequestUserFullInfo();
            $date = date("Y-m-d H:i:s");
            $status = 'pending';
            $description = '---';
            $fee = null;
            $amount = floatval($sum);
            $qSum = round($amount / 100, 2);

            insertTransaction($session->id, [
                "date" => $date,
                "status" => $status,
                "action" => $action == "dynamic" ? $action . "-" . str_replace(" ", "", $_POST["widget_id"]) : $action,
                "description" => $description,
                "sum" => $qSum,
                "fee" => $fee,
                "requestFullInfo" => $requestFullInfo,
                "payment_method" => $paymentMethod,
            ]);

            if (isset($_POST["deliveryCheckbox"]) && $_POST["deliveryCheckbox"] == "on") {
                insertDelivery($session->id, $_POST);
            }

            header("HTTP/1.1 303 See Other");
            header("Location: " . $session->url);
        }

    }

    function errorControllerStripe() {
        global $smarty, $config, $dispatcher, $db_connect;

        $eventData = $dispatcher->dispatch("payment.error.post", []);
        $defaultRedirect = $eventData["defaultRedirect"];

        $holdId = $_SESSION["balance_hold_id"] ?? 0;

        $hold = $db_connect->get("balance_holds", "*", [
            "id" => $holdId,
            "status" => "hold"
        ]);

        if ($hold) {

            $db_connect->update("users", [
                "balance[+]" => $hold["amount"]
            ], [
                "id" => $hold["user_id"]
            ]);

            $db_connect->update("balance_holds", [
                "status" => "released"
            ], [
                "id" => $holdId
            ]);

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

            if ($userBonusBalance && $userBonusBalance["status"] === "to_withdraw") {
                $db_connect->update("user_bonus_balance", [
                    "status" => "",
                    "withdraw_amount" => 0,
                ], [
                    "user_id" => $_SESSION["user_id"]
                ]);
            }

        }



        if (!empty($defaultRedirect)) {
            header("Location: " . $defaultRedirect."&status=error");
        }

        $smarty->assign('title', 'Ошибка - Mega Digital Studio');
        $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/stripe/error.tpl'));
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');
        exit;
    }

    function successControllerStripe() {
        global $db_connect, $smarty, $config, $ps_config, $user_id, $dispatcher;
        $apiToken = $ps_config[PAYMENT_METHOD]["testMode"] == true ? $ps_config[PAYMENT_METHOD]["test_api_token"] : $ps_config[PAYMENT_METHOD]["api_token"];

        \Stripe\Stripe::setApiKey($apiToken);
        if ($_GET["session_id"]) {

            $session = \Stripe\Checkout\Session::retrieve($_GET["session_id"]);
            $intendID = $session->payment_intent;
            $paymentIntent = \Stripe\PaymentIntent::retrieve($intendID);

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

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

            $rUrl = $charge->receipt_url;

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

            $data = getTransactionDataByTransactionId($_GET["session_id"]);
            $isSuccessParam = true;

            if ($data["action"] == "balance" && $data["status"] != "succeeded") {
                $transaction = $db_connect->get("transactions", "*", ["transaction_id" => $_GET["session_id"]]);

                $pendingBonus = $db_connect->get("user_bonus_transactions", "*", [
                    "transaction_id" => $_GET["session_id"],
                ]);

                if ($pendingBonus) {
                    $hasBonusBalance = $db_connect->has("user_bonus_balance", [
                        "user_id" => $_SESSION["user_id"],
                    ]);

                    if (!$hasBonusBalance) {
                        $db_connect->insert("user_bonus_balance", [
                            "user_id" => $_SESSION["user_id"],
                            "balance" => $pendingBonus["amount"]
                        ]);
                    } else {
                        $db_connect->update("user_bonus_balance", [
                            "balance[+]" => $pendingBonus["amount"]
                        ], [
                            "user_id" => $_SESSION["user_id"]
                        ]);
                    }

                    $db_connect->update("user_bonus_transactions", [
                        "status" => "success"
                    ], [
                        "transaction_id" => $_GET["session_id"]
                    ]);
                }

                deposit($currency, $transaction["sum"]);

                $balanceInfo = getConvertedBalanceInfo();
                $smarty->assign('user_balance', $balanceInfo["finalBalance"]);
                sendEmail($_SESSION["user_email"], "payment-category", "Balance");
            } elseif (str_contains($data["action"], "dynamic")) {
                $widgetId = explode("-", $data["action"])[1];
                $widget = $db_connect->get("payment_widgets", "*", ["id" => $widgetId]);

                $settings = json_decode($widget["settings"], true);
                $defaultRedirect = $settings["success_url"];
                $emailTemplate = $settings["email_template"];

                if (empty($settings["group_field"])) {
                    $settings["group_field"] = "User";
                }

                $widgetData = [
                    "data" => $data,
                    "widget" => $widget,
                    "settings" => $settings,
                    "emailTemplate" => $emailTemplate,
                    "user_id" => $user_id ?? null
                ];

                $eventData = $dispatcher->dispatch("payment.success.".$widget["w_type"], $widgetData);

                $isSuccessParam = $eventData["isSuccessParam"];
                $defaultRedirect = $eventData["defaultRedirect"] ?? $defaultRedirect;

            }else {
                $db_connect->update("balance_holds", [
                    "status" => "captured"
                ], [
                    "id" => $_SESSION["balance_hold_id"]
                ]);

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

                if ($userBonusBalance && $userBonusBalance["status"] === "to_withdraw") {
                    $db_connect->update("user_bonus_balance", [
                        "balance[-]" => $userBonusBalance["withdraw_amount"],
                        "status" => "",
                        "withdraw_amount" => 0,
                    ], [
                        "user_id" => $_SESSION["user_id"]
                    ]);
                }

                $db_connect->update("transactions", [
                    "default_redirect" => "/?myWallet&status=success"
                ], [
                    "transaction_id" => $_GET["session_id"]
                ]);

                $_SESSION["cart"] = [];
            }

            $eventData = $dispatcher->dispatch("payment.success.pre", [
                "amount" => $amount,
                "currency" => $currency,
                "status" => $status,
                "pdfUrl" => $rUrl
            ]);

            $transaction = $eventData["transaction"];

            $smarty->assign('amount', $amount);
            $smarty->assign('currency', $currency);

            if (empty($defaultRedirect)) {
                $defaultRedirect = $transaction["default_redirect"];
            }

            if (!empty($defaultRedirect)) {
                $separator = str_contains($defaultRedirect, '?') ? '&' : '?';

                if ($isSuccessParam) {
                    header("Location: " . $defaultRedirect.$separator."status=success");
                } else {
                    header("Location: " . $defaultRedirect);
                }
            }

        }


        $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/stripe/success.tpl'));
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');
        exit;
    }

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

        if (!empty($_POST["currency"]) && !empty($_POST["amount"])) {

            $currency = $_POST["currency"];
            $amount = $_POST["amount"];

            withdraw($amount, $currency);

        }

    }

    function createStripeSession($apiToken, &$sum, $ps_config, $action, $promocode)
    {
        global $db_connect, $config;
        \Stripe\Stripe::setApiKey($apiToken);
        header('Content-Type: application/json');

        $stripeCartList = array();
        $isSubscription = false;
        if ($action == "product_buy") {
          //  $sum = $_POST["price"] * 100;
            toProductBuy($stripeCartList);
        } else if ($action == "balance") {
         //   $sum = $_POST["price"] * 100;
            toDynamicTransaction($sum, "Пополнение баланса ".$config["title"], $stripeCartList);
        } else if ($action == "dynamic") {
            $widgetId = !empty($_POST["widget_id"]) ? $_POST["widget_id"] : $_GET["widget"];
            if ($widgetId) {
                $_POST["widget_id"] = $widgetId;
                $widget = $db_connect->get("payment_widgets", "*", ["id" => $_POST["widget_id"]]);

                //$sum = convertAmount($sum / 100, "RUB", getCurrentCurrency()) * 100;

                if ($widget["price"] != 0) {
                    $sum = convertAmount($widget["price"], $config["payment_info"]["default_currency"], getCurrentCurrency());
                } else {
                    $sum = $_POST['price'];
                }
                $sum = round(($sum * 100), 0);

                if ($widget["price_model"] == true || $widget["price_model"] == 1) {
                    $sum = adjustAmountByCountry($sum, getUserIP());
                }

                if ($widget["p_type"] != "recurring") {
                    if ($widget["w_type"] == "sale") {
                        toDynamicTransaction($sum, $widget["name"], $stripeCartList);
                    } else if ($widget["w_type"] == "donate") {
                        toDynamicTransaction($sum, $widget["name"], $stripeCartList);
                    } else if ($widget["w_type"] == "pay_for_hidden_data") {
                        toDynamicTransaction($sum, "Оплата скрытых данных: ".$widget["name"], $stripeCartList);
                    } else if ($widget["w_type"] == "subscription") {
                        $isSubscription = true;
                        $subscription = $db_connect->get("subscriptions", "*", ["widget_id" => $widget["id"]]);
                        $uniqId = sha1(uniqid(rand(), true));

                        $discountPercent = !empty($config["payment_info"]["default_discount_percent"]) ? $config['payment_info']['default_discount_percent'] : $subscription["discount_percent"];
                        $discountSum = !empty($config["payment_info"]["default_discount_sum"]) ? $config['payment_info']['default_discount_sum'] : $subscription["discount_sum"];

                        if (!empty($discountPercent) && $discountPercent > 1) {
                            $_POST["price"] = round($_POST["price"] - ($_POST["price"] * ($discountPercent / 100)));
                        } else if (!empty($discountSum) && $discountSum > 1) {
                            $_POST["price"] = $_POST["price"] - convertAmount($discountSum, $config["payment_info"]["default_currency"], getCurrentCurrency());
                        }

                        toDynamicTransaction($sum, "Pay subscription ".$widget["name"], $stripeCartList);
                    }
                } else {
                    toRecurringPayment($widget["name"], $widget, $apiToken);
                }

            }
        } else if ($action == "redirect-payment") {

        }

        $cartTotal = 0;
        $bonusTotal = 0;

        foreach ($stripeCartList as $c) {
            $cartTotal += ($c["unit_amount"] / 100) * $c["count"];
        }

        $paymentBonus = null;
        if (!empty($_POST["bon_id"])) {
            $bonusId = (int)$_POST["bon_id"];
            $paymentBonus = $db_connect->get("payment_bonuses", "*", [
                "id" => $bonusId,
            ]);
        }

        $bonus = 0;
        foreach ($stripeCartList as &$stripeCart) {
            $price = $stripeCart["unit_amount"] / 100;

            if (!empty($paymentBonus)) {
                if ($paymentBonus["type"] == "percent") {
                    $bonus = $price * ($paymentBonus["value"] / 100);
                } else {
                    $bonus = $paymentBonus["value"];
                }

                $bonusTotal += $bonus * $stripeCart["count"];
            } else {
                $bonus = 0;
            }
        }

        $finalTotal = $cartTotal + $bonusTotal;
        $sum = $cartTotal * 100;

        $session = doCreateTransaction($stripeCartList, $promocode);

        if ($bonus) {
            $db_connect->insert("user_bonus_transactions", [
                "user_id" => $_SESSION["user_id"],
                "amount" => $bonus,
                "status" => "pending",
                "transaction_id" => $session->id,
                "balance_after" => $db_connect->get("user_bonus_balance", "balance", ["user_id" => $_SESSION["user_id"]]) + $bonus ?? $bonus,
            ]);
        }

        if ($isSubscription) {
            $db_connect->insert("user_subscriptions", [
                "user_id" => 0,
                "subscription_id" => $subscription["id"],
                "end_date" => date("Y-m-d H:i:s", strtotime("+1 year")),
                "status" => "progress",
                "uniq_id" => $uniqId,
                "email" => $_POST["email"],
                "transaction_id" => $session->id
            ]);
        }


        return $session ?? null;
    }

    function getCountryByIP($ip) {
        $url = "http://ip-api.com/json/$ip?fields=status,message,country,regionName,city,lat,lon,query";
        $response = file_get_contents($url);
        $data = json_decode($response, true);

        if ($data['status'] == 'success') {
            return $data['country'];
        } else {
            return 'Unknown';
        }
    }

    function adjustAmountByCountry($amount, $ip) {
        global $countries;
        $country = getCountryByIP($ip);

        foreach ($countries as $data) {
            if (in_array($country, $data['countries'])) {
                $coeff = $data['yearly'];
                $adjustedAmount = $amount * $coeff;
                return $adjustedAmount;
            }
        }

        return $amount;
    }


    function toRecurringPayment($name, $widget, $apiToken)
    {
        global $ps_config;

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

        $product = \Stripe\Product::create([
            'name' => $name,
        ]);

        if ($widget["period"] == "monthly") {
            $period = "month";
        } else if ($widget["period"] == "yearly") {
            $period = "year";
        } else if ($widget["period"] == "daily") {
            $period = "day";
        } else if ($widget["period"] == "weekly") {
            $period = "week";
        }

        $plan = \Stripe\Price::create([
            'unit_amount' => adjustAmountByCountry($widget["price"], getUserIP()) * 100,
            'currency' => $_POST["currency"],
            'recurring' => ['interval' => $period],
            'product' => $product->id,
        ]);

        $session = \Stripe\Checkout\Session::create([
            'payment_method_types' => ['card'],
            'line_items' => [[
                'price' => $plan->id,
                'quantity' => 1,
            ]],
            'mode' => 'subscription',
            'success_url' => $ps_config[PAYMENT_METHOD]["successUrl"],
            'cancel_url' => $ps_config[PAYMENT_METHOD]["errorUrl"],
        ]);

        header('Location: ' . $session->url);

    }


    function toProductBuy(&$stripeCartList)
    {
        global $db_connect, $config, $user_id, $smarty;
        $productList = $_SESSION["cart"];
        $productA = array();
        foreach ($productList as $id => $product) {
            $price = 0;
            if ($product["type"] == "shop_product") {
                $productA = $db_connect->get("shop_products", "*", ["id" => $id]);
            } else {
                $productA = $db_connect->get("products", "*", ["id" => $id]);
            }

            // Получаем основной баланс
            $mainBalance = (int)$db_connect->get("users", "balance", [
                "id" => $_SESSION["user_id"],
            ]);

            // Получаем бонусный баланс
            $bonusBalance = (int)($db_connect->get("user_bonus_balance", "balance", [
                "user_id" => $_SESSION["user_id"],
            ]) ?? 0);

            // Получаем цену товара
            $price = 0;
            if (!empty($productA["price"])) {
                $price = convertAmount(
                    $productA["price"],
                    $config["payment_info"]["default_currency"],
                    getCurrentCurrency()
                );
                $price = (int) round($price * 100); // в центах
            }

            // Инициализация
            $usedFromMain  = 0;
            $usedFromBonus = 0;
            $payAmount     = $price;

            // 1. Тратим основной баланс
            if ($mainBalance > 0) {
                $usedFromMain = min($mainBalance * 100, $payAmount); // *100 чтобы работать в центах
                $payAmount -= $usedFromMain;
            }

            // 2. Тратим бонусный баланс (строго с лимитом)
            if ($payAmount > 0 && $bonusBalance > 0) {
                $usedFromBonus = min($bonusBalance * 100, $payAmount);
                $payAmount -= $usedFromBonus;
            }

            // 3. Создаём hold для основного баланса
            $holdId = 0;
            if ($usedFromMain > 0) {
                $db_connect->insert("balance_holds", [
                    "user_id" => $_SESSION["user_id"],
                    "amount"  => $usedFromMain / 100,
                    "status"  => "hold",
                ]);
                $holdId = $db_connect->id();
                $_SESSION["balance_hold_id"] = $holdId;

                // Снимаем с основного баланса
                $db_connect->update("users", [
                    "balance[-]" => $usedFromMain / 100
                ], [
                    "id" => $_SESSION["user_id"]
                ]);

                // Лог транзакции
                $action = $_POST["action"] ?? 'purchase';
                $date = date("Y-m-d H:i:s");
                $status = 'succeeded';
                $description = '---';
                $fee = null;
                $amount = $usedFromMain / 100;
                $qSum = round($amount, 2);

                insertTransaction("", [
                    "date" => $date,
                    "status" => $status,
                    "action" => $action == "dynamic" ? $action . "-" . str_replace(" ", "", $_POST["widget_id"]) : $action,
                    "description" => $description,
                    "sum" => $qSum,
                    "fee" => $fee,
                    "requestFullInfo" => [],
                    "payment_method" => "balance",
                ]);
            }

            // 4. Обновляем бонусный баланс
            if ($usedFromBonus > 0) {
                $db_connect->update("user_bonus_balance", [ "status" => "to_withdraw", "withdraw_amount" => $usedFromBonus / 100 ], [ "user_id" => $_SESSION["user_id"] ]);
            }

            // 5. Если полностью оплачено — чистим корзину и редирект
            if ($payAmount <= 0) {
                $db_connect->update("user_bonus_balance", [
                    "balance[-]" => $usedFromBonus / 100,
                    "status" => "",
                    "withdraw_amount" => 0
                ], [
                    "user_id" => $_SESSION["user_id"]
                ]);
                $db_connect->update("balance_holds", [
                    "status" => "released"
                ], [
                    "id" => $holdId
                ]);

                $_SESSION["cart"] = [];
                header("Location: /?myWallet");
                exit();
            }

            // 6. Если осталась часть на Stripe
            if ($price !== null && !empty($productA)) {
                $stripeCartList[] = [
                    'count' => $product["quantity"] ?? 1,
                    'unit_amount' => $payAmount,
                    'currency' => strtolower($_POST["currency"] ?? 'usd'),
                    'product_data' => [
                        'name' => $productA["title"] ?? $productA["name"],
                    ],
                ];
            }
        }
    }

    function toDynamicTransaction($sum, $name, &$stripeCartList)
    {
        $stripeCartList = array(
            [
                'count' => 1,
                'unit_amount' => !empty($_POST["price"]) ? $_POST["price"] * 100 : ($sum / 100) * 100,
                'currency' => strtolower($_POST["currency"]),
                'product_data' => [
                    'name' => $name,
                ],
            ]
        );
    }

    function doCreateTransaction($stripeCartList, $promocode)
    {
        global $ps_config, $db_connect;
        $lineItems = array();
        if (!empty($stripeCartList)) {
            foreach ($stripeCartList as &$stripCartAssoc) {
                $count = $stripCartAssoc["count"];
                unset($stripCartAssoc["count"]);
                $price = \Stripe\Price::create($stripCartAssoc);
                $lineItems[] = [
                    'price' => $price->id,
                    'quantity' => (int)$count,
                ];
            }

            if (!empty($promocode)) {
                try {
                    $discountData = calculateDiscount($promocode, $_POST["price"], $db_connect);

                    $coupon = \Stripe\Coupon::create([
                        'percent_off' => $discountData["discountPercent"],
                        'duration' => 'once',
                    ]);

                } catch (\Stripe\Exception\ApiErrorException $e) {
                    $coupon = null;
                }
            }


            $sessionData = array(
                'mode' => 'payment',
                'line_items' => $lineItems,
                'success_url' => $ps_config[PAYMENT_METHOD]["successUrl"],
                'cancel_url' => $ps_config[PAYMENT_METHOD]["errorUrl"],
            );

            if (isset($_POST["deliveryCheckbox"]) && $_POST["deliveryCheckbox"] == "on") {
                $sessionData["shipping_address_collection"] = ['allowed_countries' => ['US', 'CA', 'GB', 'RU', 'AM']];
                $sessionData["shipping_options"] = [
                    [
                        'shipping_rate_data' => [
                            'type' => 'fixed_amount',
                            'fixed_amount' => ['amount' => 500, 'currency' => strtolower($_POST["currency"])],
                            'display_name' => 'Стандартная дотсавка',
                            'delivery_estimate' => [
                                'minimum' => ['unit' => 'business_day', 'value' => 5],
                                'maximum' => ['unit' => 'business_day', 'value' => 7],
                            ],
                        ],
                    ],
                    [
                        'shipping_rate_data' => [
                            'type' => 'fixed_amount',
                            'fixed_amount' => ['amount' => 1500, 'currency' => strtolower($_POST["currency"])],
                            'display_name' => 'Экспресс дотсавка',
                            'delivery_estimate' => [
                                'minimum' => ['unit' => 'business_day', 'value' => 1],
                                'maximum' => ['unit' => 'business_day', 'value' => 3],
                            ],
                        ],
                    ],
                    [
                        'shipping_rate_data' => [
                            'type' => 'fixed_amount',
                            'fixed_amount' => ['amount' => 15000000, 'currency' => strtolower($_POST["currency"])],
                            'display_name' => 'Супер доставка',
                            'delivery_estimate' => [
                                'minimum' => ['unit' => 'business_day', 'value' => 1],
                                'maximum' => ['unit' => 'business_day', 'value' => 3],
                            ],
                        ],
                    ],
                ];
            }

            if (true) {
                $customer = \Stripe\Customer::create([
                    'email' => !empty($_SESSION['user_email']) ? $_SESSION['user_email'] : $_POST["email"],
                ]);

                $sessionData['customer'] = $customer->id;
            }


            if (!empty($coupon)) {
                $sessionData["discounts"] = [['coupon' => $coupon->id]];
            }

            $session = \Stripe\Checkout\Session::create($sessionData);
        }

        return $session ?? null;
    }






