<?php

namespace Shm\ShmPayment\TBankPayment;



use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Shm\Shm;
use Shm\ShmAuth\Auth;
use Shm\ShmCmd\Cmd;
use Shm\ShmDB\mDB;
use Shm\ShmPayment\TBankPayment\TBankCollections\TCustomerCards;
use Shm\ShmPayment\TBankPayment\TBankCollections\TPayments;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmTypes\StructureType;
use Shm\ShmUtils\ShmTwig;
use Shm\ShmUtils\ShmUtils;

class TBankPayment
{


    const API_ENDPOINT = 'https://securepay.tinkoff.ru/v2/';

    const WEBHOOK_URL = '/webhook/tbank/payment';

    //TODO не понятно придет ли 10 рублей на счет или 9,70
    //Чуть позже проверить и если не 10 рублей то считать сколько придет
    const BANK_COMMISSION = 0.03;

    protected static  $default_http_client_options = [
        'connect_timeout' => 4,
        'timeout' => 10
    ];

    public static $terminalKey = null;
    public static $terminalPassword =  null;


    /**
     * Система налогообложения
     * osn - общая СН
     * usn_income - упрощенная СН (доходы)
     * usn_income_outcome - упрощенная СН (доходы минус расходы)
     * esn - единый сельскохозяйственный налог
     * patent - патентная СН
     */
    public static $terminalTaxation = null;

    /**
     * Налоговая ставка
     * none - без НДС
     * vat0 - НДС по ставке 0%
     * vat5 - НДС по ставке 5%
     * vat7 - НДС по ставке 7%
     * vat10 - НДС по ставке 10%
     * vat22 - НДС по ставке 22%
     * vat105 - НДС чека по расчетной ставке 5/105
     * vat107 - НДС чека по расчетной ставке 7/107
     * vat110 - НДС чека по расчетной ставке 10/110
     * vat122 - НДС чека по расчетной ставке 22/122
     */
    public static $terminalTaxRate = null;





    public $customerID = null;
    public $customerPhone = null;
    public $customerStructure = null;

    public static function setTerminalTaxation($taxation)
    {
        self::$terminalTaxation = $taxation;
    }
    public static function setTerminalTaxRate($taxRate)
    {
        self::$terminalTaxRate = $taxRate;
    }



    public static function setTerminalKey($terminalKey)
    {
        self::$terminalKey = $terminalKey;
    }
    public static function setTerminalPassword($password)
    {
        self::$terminalPassword = $password;
    }

    public function __construct(StructureType $customerStructure, $customer_id)
    {


        if (!self::$terminalKey || !self::$terminalPassword) {
            throw new \Exception("Terminal key or password is not set");
        }


        if (!self::$terminalTaxation) {
            throw new \Exception("Terminal taxation is not set");
        }

        if (!self::$terminalTaxRate) {
            throw new \Exception("Terminal tax rate is not set");
        }

        $this->customerStructure = $customerStructure;

        $phoneField = $customerStructure->findItemByType(Shm::phone());
        if (!$phoneField) {
            throw new \Exception("Phone field not found");
        }

        $customer = $customerStructure->findOne([
            "_id" => mDB::id($customer_id),
            $phoneField->key => [
                '$exists' => true,
                '$ne' => null,
            ]
        ]);

        if (!$customer) {
            throw new \Exception("Customer not found");
        }

        $this->customerID =  $customer['_id'];
        $this->customerPhone = '+' . $customer[$phoneField->key];
    }


    public function getCustomerKey()
    {
        return md5($this->customerID) . '-' .  md5($this->customerStructure->collection) . '-' . md5(self::$terminalKey);
    }

    public static function updatePaymentState($payment_id)
    {

        $payment = TPayments::findOne([
            '_id' => mDB::id($payment_id),

        ]);
        if (!$payment) {
            throw new \Exception("Payment not found");
        }

        $paymentId = $payment['paymentId'] ?? $payment['initResult']['PaymentId'];




        $data = [
            'PaymentId' => $paymentId,
        ];
        $response = self::sendRequest('GetState', $data);

        TPayments::updateOne(
            [
                '_id' => mDB::id($payment_id)
            ],
            [
                '$set' => ['status' => $response['Status']]
            ]
        );

        // var_dump($response['Status']);
    }



    public static function CustomerCardsRpc()
    {

        return ShmRPC::makeQuery(TCustomerCards::structure())->pipeline(function () {

            Auth::authenticateOrThrow();

            return [
                [
                    '$match' => [
                        'TerminalKey' => self::$terminalKey,
                        'owner' => Auth::getAuthID(),
                        'ownerCollection' => Auth::getAuthCollection()
                    ]
                ]
            ];
        });
    }

    public function getCustomerCards()
    {
        $response = self::sendRequest('GetCardList', [
            "CustomerKey" => $this->getCustomerKey(),
            'TerminalKey' => self::$terminalKey,
            'owner' => mDB::id($this->customerID),
            'ownerCollection' => $this->customerStructure->collection,
        ]);
        return $response;
    }

    public function syncCustomerCards()
    {
        $response = self::sendRequest('GetCardList', [
            "CustomerKey" => $this->getCustomerKey(),
        ]);


        $cards = $response ?? [];

        foreach ($cards as $card) {

            TCustomerCards::updateOne(
                [
                    'CardId' => $card['CardId'],
                    'deleted_at' => ['$exists' => false],
                    "owner" => mDB::id($this->customerID),
                    "ownerCollection" => $this->customerStructure->collection,
                    'TerminalKey' => self::$terminalKey,

                ],
                [

                    '$set' => [
                        ...$card,
                        'TerminalKey' => self::$terminalKey,
                        "owner" => mDB::id($this->customerID),
                        "ownerCollection" => $this->customerStructure->collection,
                    ]

                ],
                [
                    'upsert' => true,
                ]
            );
        }
    }

    public  function GetCustomer()
    {
        $response = self::sendRequest('GetCustomer', [
            'CustomerKey' => $this->getCustomerKey(),
        ]);

        return $response;
    }

    public function Cancel($PaymentId)
    {
        $response = self::sendRequest('Cancel', [
            "PaymentId" => $PaymentId,
        ]);

        return $response;
    }

    public function Charge($PaymentId, $RebillId)
    {
        $response = self::sendRequest('Charge', [
            "PaymentId" => $PaymentId,
            "RebillId" => $RebillId,
        ]);
        return $response;
    }

    public function addCard()
    {



        /*

        Тут есть метод добавления карты, но он не работает,
        Поэтому используем метод оплаты чтобы сохранить карту
        $data = [
            'CustomerKey' => $this->getCustomerKey(),
            'NotificationURL' => ShmUtils::url(self::WEBHOOK_URL),
            // 'CheckType' => "HOLD",
            "ResidentState" => true
        ];

        $response = self::sendRequest('AddCard', $data);

        var_dump($response);*/
    }


    public  function initPayment($sum, $description, $autoRefunded = false): ?string
    {

        $orderId = uniqid() . '' . uniqid() . 'order';

        $data = [
            'Amount' => $sum * 100,
            'OrderId' => $orderId,
            'Description' => $description,
            'DATA' => [
                'Phone' => $this->customerPhone,
            ],
            'Recurrent' => 'Y',
            'CustomerKey' => $this->getCustomerKey(),

            'NotificationURL' => ShmUtils::url(self::WEBHOOK_URL),
        ];

        $data['SuccessURL'] = ShmUtils::url('/payment/status/success');
        $data['FailURL'] = ShmUtils::url('/payment/status/error');


        $data['Receipt'] = [
            'Phone' => $this->customerPhone,
            "Taxation" => self::$terminalTaxation,
            "Items" => [
                [
                    "Name" => $description,
                    "Price" => $sum * 100,
                    "Quantity" => 1,
                    "Amount" => $sum * 100,
                    "Tax" => self::$terminalTaxRate
                ]
            ],
        ];



        $payment = TPayments::insertOne([
            "amount" => $sum,
            "orderId" => $orderId,
            "description" => $description,
            "phone" => $this->customerPhone,
            "owner" => mDB::id($this->customerID),
            "ownerCollection" => $this->customerStructure->collection,
            'initRequest' => $data,
            'terminalKey' => self::$terminalKey,
            'autoRefunded' => $autoRefunded,
        ]);


        $response = self::sendRequest('Init', $data);

        TPayments::updateOne(
            [
                '_id' => $payment->getInsertedId()
            ],
            [
                '$set' => [
                    'status' => $response['Status'] ?? "INIT_ERROR",
                    'paymentId' => $response['PaymentId'] ?? null,
                    'initResult' => $response
                ]
            ]
        );

        return $response['PaymentURL'] ?? null;
    }

    public function removeCard($CardId)
    {

        $response = self::sendRequest('RemoveCard', [
            "CardId" => $CardId,
            "CustomerKey" => $this->getCustomerKey(),
        ]);

        return $response;
    }


    protected static function generateToken(array $params)
    {
        foreach (['SHOPS', 'RECEIPT', 'DATA'] as $ignore_key) {
            if (isset($params[$ignore_key])) {
                unset($params[$ignore_key]);
            }
        }

        $params['Password'] = self::$terminalPassword;
        ksort($params);

        $token = '';
        foreach ($params as $param_value) {
            if (is_scalar($param_value)) {
                $token .= $param_value;
            }
        }

        return hash('sha256', $token);
    }

    public  static function sendRequest($method, $data)
    {


        $data['TerminalKey'] = self::$terminalKey;


        $data['Token'] = self::generateToken($data);
        $url = self::API_ENDPOINT . $method;




        $headers = [
            'Content-Type' => 'application/json',
        ];


        $client = new Client(self::$default_http_client_options);


        $request = new Request('POST', $url, $headers, json_encode($data));
        $response = $client->sendAsync($request)->wait();


        $body = json_decode($response->getBody(), true);



        return $body;
    }


    public static function routesInit()
    {


        Cmd::command("tbankWorker", function () {


            //Проверка операций которые надо отменить 
            $operation = TPayments::findOne([
                'status' => 'CONFIRMED',
                'autoRefunded' => true,
            ]);


            if ($operation) {


                $paymentId = $operation['paymentId'] ?? null;
                if ($paymentId) {
                    $response = self::sendRequest('Cancel', [
                        "PaymentId" => $paymentId,
                    ]);

                    $status = $response['Status'] ?? null;

                    $set = [
                        'cancelResult' => $response,
                    ];
                    if ($status) {
                        $set['status'] = $status;
                    }
                }
            }
        })->everyMinute();


        $f3 = \Base::instance();
        $f3->route('POST|GET ' . self::WEBHOOK_URL, function ($f3) {

            $data = ShmUtils::allRequest();

            $OrderId = $data['OrderId'] ?? null;

            if ($OrderId) {

                $payment = TPayments::findOne([
                    'orderId' => $OrderId
                ]);

                if ($payment) {

                    $notifications = $payment->notifications ?? [];
                    $notifications = (array) $notifications;
                    $notifications[] = $data;

                    $status = $data['Status'] ?? null;


                    TPayments::updateOne([
                        '_id' => $payment['_id']
                    ], [
                        '$set' => [
                            'status' => $status,
                            'notifications' => $notifications
                        ]

                    ]);
                }
            }
        });

        $f3->route('GET /payment/status/success', function ($f3) {
            ShmTwig::html('@shm/payment/payment_success.twig');
        });
        $f3->route('GET /payment/status/error', function ($f3) {
            ShmTwig::html('@shm/payment/payment_error.twig');
        });
    }
}