<?php

namespace Myvetshop\Module\Clinique\Accounting\Export\Exporter\Provider\BankCharge;

use Myvetshop\Module\Clinique\Accounting\Export\Exporter\Provider\BankCharge\Computer\BankChargeComputerFactory;
use Myvetshop\Module\Clinique\Accounting\Export\Exporter\Provider\OrderInvoiceLineProviderInterface;
use Myvetshop\Module\Clinique\Accounting\Export\Exporter\Provider\OrderSlipLineProviderInterface;
use Myvetshop\Module\Clinique\Accounting\Export\Model\SimpleAccountingLine;
use Myvetshop\Module\Clinique\Accounting\Export\Repository\OrderPaymentRepository;

class BankChargeProvider implements OrderInvoiceLineProviderInterface, OrderSlipLineProviderInterface
{
    protected BankChargeComputerFactory $bankChargeComputerFactory;

    protected OrderPaymentRepository $orderPaymentRepository;

    public function __construct(
        BankChargeComputerFactory $paymentExporterFactory,
        OrderPaymentRepository $orderPaymentRepository
    ) {
        $this->bankChargeComputerFactory = $paymentExporterFactory;
        $this->orderPaymentRepository = $orderPaymentRepository;
    }

    public function getInvoiceAccountingLines(\OrderInvoice $orderInvoice, \Order $order): array
    {
        $ret = [];

        $totalCharges = 0.0;

        foreach ($this->orderPaymentRepository->getByOrderInvoice($orderInvoice) as $orderPayment) {
            $totalCharges += $this->bankChargeComputerFactory
                ->create($orderPayment)
                ->computeBankCharges($orderPayment->amount);
        }

        if ($totalCharges > 0) {
            $ret[] = new SimpleAccountingLine('627', 0.00, $totalCharges);
            $ret[] = new SimpleAccountingLine('4000018', $totalCharges, 0.00);
        }

        return $ret;
    }

    public function getSlipAccountingLines(\OrderSlip $orderSlip, \Order $order): array
    {
        $ret = [];

        $orderPayment = $this->orderPaymentRepository->getByOrder($order)[0] ?? null;

        if ($orderPayment) {
            $chargeComputer = $this->bankChargeComputerFactory->create($orderPayment);

            $amount = $orderSlip->total_products_tax_incl + $orderSlip->total_shipping_tax_incl;

            if ($orderSlip->order_slip_type == 1) {
                $amount -= $order->total_discounts_tax_incl;
            }

            $totalCharges = $chargeComputer->computeBankCharges($amount);

            if ($totalCharges) {
                $ret[] = new SimpleAccountingLine('627', $totalCharges, 0.00);
                $ret[] = new SimpleAccountingLine('4000018', 0.00, $totalCharges);
            }
        }

        return $ret;
    }

    /**
     * @param \OrderInvoice|\OrderSlip $document
     */
    public function getAccountingLines($document, \Order $order): array
    {
        return $document instanceof \OrderInvoice
            ? $this->getInvoiceAccountingLines($document, $order)
            : $this->getSlipAccountingLines($document, $order);
    }
}
