<?php

declare(strict_types=1);

namespace KupShop\ReturnsBundle\Attachment;

use KupShop\KupShopBundle\Email\EmailGroupTypeEnum;
use KupShop\KupShopBundle\Util\Pdf\HTMLToPDF;
use KupShop\OrderingBundle\Attachment\BaseAttachment;
use KupShop\ReturnsBundle\Entity\ReturnEntity;
use KupShop\ReturnsBundle\Util\ReturnsUtil;

class ReturnPDFAttachment extends BaseAttachment
{
    protected static $name = 'Vratka';
    protected static $type = 'return';
    protected static $group = EmailGroupTypeEnum::RETURN;

    protected $filename = 'Vratka_{KOD}.pdf';
    protected $template = 'returns/pdf/returnPDF.tpl';

    private ?ReturnEntity $return = null;

    private HTMLToPDF $htmlToPdf;
    private ReturnsUtil $returnsUtil;

    public function __construct(HTMLToPDF $htmlToPdf, ReturnsUtil $returnsUtil)
    {
        $this->htmlToPdf = $htmlToPdf;
        $this->returnsUtil = $returnsUtil;
    }

    public function getFilename(): string
    {
        return $this->returnsUtil->replacePlaceholders($this->filename, ['KOD' => $this->return->getCode()]);
    }

    public function setReturn(ReturnEntity $return): void
    {
        $this->return = $return;
    }

    public function getContent()
    {
        $order = $this->returnsUtil->getReturnOrder((int) $this->return->getId());

        $bankAccount = $this->return->getBankAccount();

        $bank = ['account_number' => $bankAccount, 'iban' => null];
        if (!empty($bankAccount)) {
            $iban = new \PHP_IBAN\IBAN($bankAccount);
            $isValidIBAN = $iban->Verify();
            $accountNo = $bankAccount;
            if ($isValidIBAN && $iban->Country() === 'CZ') {
                $accountNo = $iban->Branch().'-'.$iban->Account().'/'.$iban->Bank();
            }

            $bank = [
                'account_number' => $accountNo,
                'iban' => $isValidIBAN ? $bankAccount : null,
            ];
        }

        $smarty = createSmarty(false, true);
        $smarty->assign([
            'return' => $this->return,
            'order' => $order,
            'bank' => $bank,
        ]);

        $content = $smarty->fetch($this->template);

        return $this->htmlToPdf->generatePDF($content, null, true);
    }
}
