<?php

namespace Shm\ShmPayment\TBankPayment;

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

class TBankInitPayment
{


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


    public $orderId;

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

    /**
     * @var TBankReceiptItem[]
     */
    public $Items = [];
    private $totalAmountKopecks = 0;
    private $manualAmount = false;

    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->manualAmount = true;
        $this->totalAmountKopecks = TBankAmount::toKopecks($totalAmount);
        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)
    {
        if ($this->manualAmount) {
            throw new \Exception("Нельзя добавить товары если установлен totalAmount");
        }
        $this->Items[] = $item;
        $this->totalAmountKopecks += $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->totalAmountKopecks <= 0) {
            return false;
        }

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


        return true;
    }

    public function request()
    {


        $data = [
            'Amount' => $this->totalAmountKopecks,
            '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->totalAmountKopecks,
                        "Quantity" => 1,
                        "Amount" => $this->totalAmountKopecks,
                        "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([
            TPaymentsField::AMOUNT => TBankAmount::toRubles($this->totalAmountKopecks),
            TPaymentsField::ORDER_ID => $this->orderId,
            TPaymentsField::DESCRIPTION => $this->description,
            TPaymentsField::PHONE => $this->customer->customerPhone,
            TPaymentsField::EMAIL => $this->customer->customerEmail,
            TPaymentsField::OWNER => $this->customer->customerID,
            TPaymentsField::OWNER_COLLECTION => $this->customer->customerStructure->collection,
            TPaymentsField::INIT_REQUEST => $data,
            'terminalKey' => TBankPayment::$terminalKey,
            TPaymentsField::AUTO_REFUNDED => $this->autoRefunded,
            TPaymentsField::NOTIFICATIONS => [],
            'payload' => $this->payload,
        ]);


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

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

        TPayments::updateOne(
            [
                TPaymentsField::_ID => $payment->getInsertedId()
            ],
            [
                '$set' => [
                    TPaymentsField::STATUS => $response['Status'] ?? "INIT_ERROR",
                    TPaymentsField::PAYMENT_ID => $response['PaymentId'] ?? null,
                    TPaymentsField::INIT_RESULT => $response
                ]
            ]
        );
        $this->paymentId = $response['PaymentId'] ?? null;
    }
}
