<?php

namespace KupShop\OrderingBundle\Attachment;

use KupShop\KupShopBundle\Email\EmailGroupTypeEnum;
use KupShop\OrderingBundle\Exception\InvoiceException;
use KupShop\OrderingBundle\Util\Invoice\PdfGenerator;

class InvoicePDFAttachment extends BaseAttachment
{
    protected static $name = 'Faktura';
    protected static $type = 'order_invoice';
    protected static $priority = 500;
    protected static $group = EmailGroupTypeEnum::ORDER;

    protected $filename = 'Faktura_{KOD}.pdf';
    protected $template = 'invoicePDF';

    private $pdfGenerator;

    public function __construct(PdfGenerator $pdfGenerator)
    {
        $this->pdfGenerator = $pdfGenerator;
    }

    public function getFilename(): string
    {
        $dbcfg = \Settings::getDefault();
        $filename = $dbcfg->invoice_name;
        if (empty($filename)) {
            return $this->order->replacePlaceholders(translate_shop('invoice_filename', 'attachments'));
        }
        if (!str_contains($filename, '{')) {
            $filename .= '_{KOD}';
        }
        $filename = $this->order->replacePlaceholders($filename);
        $filename .= '.pdf';

        return $filename;
    }

    public function getContent()
    {
        if ($externalInvoiceUrl = ($this->order->getData('externalDocuments')[static::getType()] ?? null)) {
            return file_get_contents($externalInvoiceUrl);
        }

        if ($this->order->getInvoiceNo()) {
            return $this->pdfGenerator->setTemplate($this->getTemplate())->getInvoicePDFContent($this->order->id);
        }

        throw new InvoiceException("Nelze vytisknout fakturu - objednávka (ID {$this->order->id}) ještě nebyla fakturována.");
    }
}
