<?php

namespace Shm\ShmPayment\TBankPayment;

use Shm\ShmPayment\TBankPayment\TBankCollections\TPayments;

class TBankCancel
{
    public $paymentId;

    public $amount = null;

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

    public $success = false;

    public $status;

    public $originalAmount;

    public $newAmount;

    public $description;

    public function __construct() {}

    public static function create($paymentId)
    {
        $TBankCancel = new TBankCancel();
        $TBankCancel->paymentId($paymentId);
        return $TBankCancel;
    }

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

    public function amount($amount)
    {
        if ($amount <= 0) {
            throw new \Exception("amount должно быть больше 0");
        }
        if (count($this->Items) > 0) {
            throw new \Exception("Нельзя установить amount если есть товары Items: " . count($this->Items));
        }
        $this->amount = $amount * 100;
        return $this;
    }

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

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

    public function readyToRequest(): bool
    {
        if (!$this->paymentId) {
            return false;
        }

        return true;
    }

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

    private function originalAmountInKopecks($payment): int
    {
        return (int) round($payment['initRequest']['Amount'] ?? ($payment['amount'] * 100));
    }

    private function isFullRefund($payment): bool
    {
        return $this->amount !== null && (int) $this->amount === $this->originalAmountInKopecks($payment);
    }

    private function isPartialCancel(): bool
    {
        return $this->amount !== null || count($this->Items) > 0;
    }

    public function request()
    {
        $payment = TPayments::findOne([
            'paymentId' => $this->paymentId,
        ]);

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

        $data = [
            'PaymentId' => $this->paymentId,
        ];

        if ($this->amount !== null) {
            $data['Amount'] = $this->amount;
        }

        if ($this->isPartialCancel() && !$this->isFullRefund($payment)) {
            if (count($this->Items) > 0) {
                $data['Receipt'] = [
                    "Taxation" => TBankPayment::$terminalTaxation,
                    "Items" => $this->prepareItems(),
                ];
            } else {
                $description = $this->description ?? $payment['description'] ?? null;
                if (!$description) {
                    throw new \Exception("description обязательно если нет товаров Items");
                }

                $data['Receipt'] = [
                    "Taxation" => TBankPayment::$terminalTaxation,
                    "Items" => [
                        [
                            "Name" => $description,
                            "Price" => $this->amount,
                            "Quantity" => 1,
                            "Amount" => $this->amount,
                            "Tax" => TBankPayment::$terminalTaxRate
                        ]
                    ],
                ];
            }

            if ($payment['phone'] ?? null) {
                $data['Receipt']['Phone'] = $payment['phone'];
            }
            if ($payment['email'] ?? null) {
                $data['Receipt']['Email'] = $payment['email'];
            }
        }

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

        $this->success = $response['Success'] ?? false;
        $this->status = $response['Status'] ?? null;
        $this->originalAmount = $response['OriginalAmount'] ?? null;
        $this->newAmount = $response['NewAmount'] ?? null;

        $update = [
            '$push' => [
                'cancelResult' => [
                    'request' => $data,
                    'result' => $response,
                    'created_at' => time(),
                ],
            ],
        ];
        if ($this->status) {
            $update['$set']['status'] = $this->status;
        }

        TPayments::updateOne(
            [
                '_id' => $payment['_id']
            ],
            $update
        );

        return $response;
    }
}
