<?php

namespace Shm\ShmPayment\TBankPayment;

use Shm\ShmPayment\TBankPayment\TBankCollections\TPayments;
use Shm\ShmUtils\ShmUtils;

class TBankInitPayment
{


    public $paymentId;
    public $success = false;
    //PaymentURL
    public $paymentURL;


    public $orderId;

    /**
     * @var TBankCustomer
     */
    public $customer;

    /**
     * @var TBankReceiptItem[]
     */
    public $Items = [];
    public $totalAmount = 0;

    public $autoRefunded = false;

    public $description;

    public $payload = [];

    public function payload($payload)
    {
        $this->payload = $payload;
        return $this;
    }

    public function totalAmount($totalAmount)
    {
        if ($totalAmount <= 0) {
            throw new \Exception("totalAmount должно быть больше 0");
        }
        if (count($this->Items) > 0) {

            //Ошибка что нельзя установить totalAmount если есть товары
            throw new \Exception("Нельзя установить totalAmount если есть товары Items: " . count($this->Items));
        }
        $this->totalAmount = $totalAmount * 100;
        return $this;
    }

    public function autoRefunded($autoRefunded = true)
    {
        $this->autoRefunded = $autoRefunded;
        return $this;
    }

    public static function create(TBankCustomer $customer)
    {
        return new self($customer);
    }

    public  function __construct(TBankCustomer $customer)
    {
        $this->orderId = uniqid() . '' . uniqid() . 'order';
        $this->customer = $customer;
    }

    public function addItem(TBankReceiptItem $item)
    {
        $this->Items[] = $item;
        $this->totalAmount += $item->amount();
    }

    public function description($description)
    {
        $this->description = $description;
        return $this;
    }

    private function prepareItems()
    {
        return array_map(function (TBankReceiptItem $item) {
            return $item->toArray();
        }, $this->Items);
    }

    public function readyToRequest(): bool
    {

        if ($this->totalAmount <= 0) {
            return false;
        }

        if (!$this->description) {
            return false;
        }


        return true;
    }

    public function request()
    {


        $data = [
            'Amount' => $this->totalAmount,
            'OrderId' => $this->orderId,
            'Description' => $this->description,
            'Recurrent' => 'Y',
            'CustomerKey' => $this->customer->getCustomerKey(),
            'NotificationURL' => ShmUtils::url(TBankPayment::WEBHOOK_URL),
        ];

        if ($this->customer->customerPhone) {
            $data['DATA']['Phone'] = $this->customer->customerPhone;
        }
        if ($this->customer->customerEmail) {
            $data['DATA']['Email'] = $this->customer->customerEmail;
        }

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


        if (count($this->Items) > 0) {
            $data['Receipt'] = [
                "Taxation" => TBankPayment::$terminalTaxation,
                "Items" => $this->prepareItems(),
            ];
        } else {
            $data['Receipt'] = [
                "Taxation" => TBankPayment::$terminalTaxation,
                "Items" => [
                    [
                        "Name" => $this->description,
                        "Price" => $this->totalAmount,
                        "Quantity" => 1,
                        "Amount" => $this->totalAmount,
                        "Tax" => TBankPayment::$terminalTaxRate
                    ]
                ],
            ];
        }
        if ($this->customer->customerPhone) {
            $data['Receipt']['Phone'] = $this->customer->customerPhone;
        }
        if ($this->customer->customerEmail) {
            $data['Receipt']['Email'] = $this->customer->customerEmail;
        }



        $payment = TPayments::insertOne([
            "amount" => $this->totalAmount / 100,
            "orderId" => $this->orderId,
            "description" => $this->description,
            "phone" => $this->customer->customerPhone,
            "email" => $this->customer->customerEmail,
            "owner" => $this->customer->customerID,
            "ownerCollection" => $this->customer->customerStructure->collection,
            'initRequest' => $data,
            'terminalKey' => TBankPayment::$terminalKey,
            'autoRefunded' => $this->autoRefunded,
            'notifications' => [],
            'payload' => $this->payload,
        ]);


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

        $this->success = $response['Success'] ?? false;
        $this->paymentURL = $response['PaymentURL'] ?? null;

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