<?php

namespace Shm\ShmPayment;

use Shm\ShmDB\mDB;
use Shm\ShmHttp\ShmHttp;
use Shm\ShmTypes\CompositeTypes\BalanceTypes\BalanceGateway;
use Shm\ShmTypes\CompositeTypes\BalanceTypes\BalanceType;
use Shm\ShmTypes\StructureType;
use Shm\ShmUtils\ShmDoctor\Utils\StructureHelper;
use Shm\ShmUtils\ShmInit;
use Shm\ShmUtils\ShmUtils;

class ShmAppTorPayment
{
    public static function yoomoneyGateway($functionStructure): BalanceGateway
    {


        $gateway = new BalanceGateway('yoomoney');
        $gateway->setTitle('Картой онлайн');
        $gateway->setDescription('Оплата картой онлайн');
        $gateway->setMinAmount(1000);
        $gateway->setMaxAmount(15000);
        $gateway->setPaymentLinkGenerator(function ($user_id, $amount) use ($functionStructure): string {



            $structure = $functionStructure();

            $result = ShmHttp::post("https://payment.wgt.click/api/payment", [
                'method' => "yoomoney",
                'params' => [
                    "amount" => $amount,
                    'currency' => "RUB",
                    'webhook' => self::url('/appTorPayment/webhook'),
                    'payload' => [
                        "owner" => $user_id,
                        'ownerCollection' => $structure->collection,
                        'amount' => $amount,
                        'currency' => "RUB",
                        'gateway' => "yoomoney",
                    ],
                ]
            ]);


            mDB::collection("_appTorPayment")->insertOne($result['result']);


            return $result['result']['link'];
        });


        return $gateway;
    }

    public static function invoiceGateway($functionStructure): BalanceGateway
    {
        $gateway = new BalanceGateway('invoice');
        $gateway->setTitle('Оплат по счету');
        $gateway->setDescription('Оплата по счету');

        $gateway->setPaymentLinkGenerator(function ($user_id, $amount) use ($functionStructure): string {


            $structure = $functionStructure();

            $result = ShmHttp::post("https://payment.wgt.click/api/payment", [
                'method' => "invoice",
                'params' => [
                    "amount" => $amount,
                    'info' => "Пополнение баланса личного кабинета №" . $user_id . " по договору-оферте. Без НДС.",
                    'currency' => "RUB",
                    'payload' => [
                        "owner" =>  mDB::id($user_id),
                        'ownerCollection' => $structure->collection,
                        'amount' => $amount,
                        'currency' => "RUB",
                        'gateway' => "invoice",
                    ],
                ]
            ]);


            mDB::collection("_appTorPayment")->insertOne($result['result']);


            return $result['result']['link'];
        });
        return $gateway;
    }

    private static function url($path = "")
    {


        $scheme =  (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';

        $host = $_SERVER['HTTP_HOST'] ?? "";

        $currentURL = $scheme . '://' . $host;

        return $currentURL . $path;
    }

    public static function webhookInit()
    {

        $f3 = \Base::instance();
        $f3->route('POST|GET /appTorPayment/webhook', function ($f3) {


            $data = ShmUtils::allRequest();
            $status = $data['status'] ?? null;
            $payload = $data['payload'] ?? null;

            if (!$status || !$payload) {

                return;
            }

            $currency = $payload['currency'] ?? null;

            $amount = $payload['amount'] ?? null;

            if (!$amount) {
                return;
            }

            $owner = $payload['owner'] ?? null;
            $ownerCollection = $payload['ownerCollection'] ?? null;
            if (!$owner || !$ownerCollection) {
                return;
            }

            $owner = mDB::id($owner);


            $findStructure = StructureHelper::getStructureByCollection($ownerCollection);
            if (!$findStructure) {
                return;
            }

            $paymentItems = $findStructure->findItemsByCondition(function ($item) use ($currency) {
                if ($item instanceof BalanceType) {


                    if ($item->currency == $currency) {
                        return true;
                    }
                }
                return false;
            });



            $paymentItem = $paymentItems[0] ?? null;

            if (!$paymentItem) {
                return;
            }

            if ($paymentItem instanceof BalanceType) {

                $paymentItem->addCurrencyBalance($owner, $amount, "Пополнение баланса личного кабинета #" . $owner);
            } else {
                return;
            }
        });
    }
}
