<?php

namespace common\logic\Document\Document\Service;

use common\helpers\GlobalParam;
use common\logic\AbstractService;
use common\logic\Document\Document\Model\DocumentInterface;
use common\logic\Producer\Producer\Repository\ProducerRepository;
use common\logic\Producer\Producer\Service\ProducerSolver;
use common\logic\UtilsInterface;
use kartik\mpdf\Pdf;
use yii\base\ErrorException;
use yii\helpers\Html;

class DocumentUtils extends AbstractService implements UtilsInterface
{
    protected DocumentSolver $documentSolver;
    protected DocumentBuilder $documentBuilder;
    protected ProducerSolver $producerSolver;
    protected ProducerRepository $producerRepository;

    public function loadDependencies(): void
    {
        $this->documentSolver = $this->loadService(DocumentSolver::class);
        $this->documentBuilder = $this->loadService(DocumentBuilder::class);
        $this->producerSolver = $this->loadService(ProducerSolver::class);
        $this->producerRepository = $this->loadService(ProducerRepository::class);
    }

    public function generatePdf(DocumentInterface $document, string $destination): ?string
    {
        $producer = $document->producer;
        $content = \Yii::$app->controller->renderPartial('/document/download', [
            'producer' => $producer,
            'document' => $document
        ]);

        $contentFooter = '<div id="footer">';
        $contentFooter .= '<div class="infos-bottom">' . Html::encode($producer->document_infos_bottom) . '</div>';
        if ($this->documentSolver->isStatusValid($document) || $this->documentSolver->isStatusDraft($document)) {
            $contentFooter .= '<div class="reference-document">';
            if ($this->documentSolver->isStatusValid($document)) {
                $contentFooter .= $this->documentSolver->getType($document) . ' N°' . $document->reference;
            }
            if ($this->documentSolver->isStatusDraft($document)) {
                $contentFooter .= $this->documentSolver->getType($document) . ' non validé';
                if ($this->documentSolver->getType($document) == 'Facture') {
                    $contentFooter .= 'e';
                }
            }
            $contentFooter .= '</div>';
        }
        $contentFooter .= '</div>';

        $marginBottom = 10;
        if (strlen($this->producerRepository->getConfig('document_infos_bottom')) > 0) {
            $marginBottom = 40;
        }

        $this->initDirectoryPdf($document);

        $pdf = new Pdf([
            'mode' => Pdf::MODE_UTF8,
            'format' => Pdf::FORMAT_A4,
            'orientation' => Pdf::ORIENT_PORTRAIT,
            'destination' => $destination,
            'content' => $content,
            'filename' => $this->documentSolver->getFilenameComplete($document),
            'cssFile' => \Yii::getAlias('@webroot/css/document/download.css'),
            'marginBottom' => $marginBottom,
            'methods' => [
                'SetHTMLFooter' => $contentFooter
            ]
        ]);

        return $pdf->render();
    }

    public function initDirectoryPdf(DocumentInterface $document): void
    {
        $aliasDirectoryBase = $this->documentSolver->getAliasDirectoryBase($document);
        $directoryPdf = \Yii::getAlias($aliasDirectoryBase);
        if (!file_exists($directoryPdf)) {
            //die('dir : '.$directoryPdf);
            mkdir($directoryPdf, 0755);
        }
    }

    public function downloadPdf(DocumentInterface $document, bool $regenerate = false)
    {
        $filenameComplete = $this->documentSolver->getFilenameComplete($document);

        if (!file_exists($filenameComplete) || $this->documentSolver->isStatusDraft($document) || $regenerate) {
            $this->generatePdf($document, Pdf::DEST_FILE);
        }

        if (file_exists($filenameComplete)) {
            return \Yii::$app->response->sendFile($filenameComplete, $this->documentSolver->getFilename($document), ['inline' => true]);
        } else {
            throw new ErrorException('File ' . $filenameComplete . ' not found');
        }
    }

    public function send(DocumentInterface $document): bool
    {
        if (isset($document->user) && strlen($document->user->email) > 0) {
            $producer = GlobalParam::getCurrentProducer();

            $subjectEmail = $this->documentSolver->getType($document);
            if ($this->documentSolver->isStatusValid($document)) {
                $subjectEmail .= ' N°' . $document->reference;
            }

            $email = \Yii::$app->mailer->compose(
                [
                    'html' => 'sendDocument-html',
                    'text' => 'sendDocument-text'
                ], [
                'document' => $document
            ])
                ->setTo($document->user->email)
                ->setFrom([$this->producerSolver->getEmailOpendistrib($producer) => $producer->name])
                ->setSubject('[' . $producer->name . '] ' . $subjectEmail);

            $this->generatePdf($document, Pdf::DEST_FILE);
            $email->attach($this->documentSolver->getFilenameComplete($document));

            return $email->send();
        }

        return false;
    }
}