<?php

namespace common\logic\Document\Document\Service;

use common\logic\AbstractManager;
use common\logic\Document\Document\Model\Document;
use common\logic\Document\Document\Model\DocumentInterface;
use common\logic\Producer\Producer\Service\ProducerSolver;
use kartik\mpdf\Pdf;
use yii\base\ErrorException;
use yii\helpers\Html;

class DocumentManager extends AbstractManager
{
    protected DocumentSolver $documentSolver;
    protected DocumentBuilder $documentBuilder;
    protected ProducerSolver $producerSolver;
    protected DocumentReferenceGenerator $documentReferenceGenerator;

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

    public function changeStatus(DocumentInterface $document, string $status): void
    {
        $document->status = $status;

        if ($status == Document::STATUS_VALID) {
            $this->documentReferenceGenerator->generateReference($document);
        }

        $this->documentBuilder->update($document);
    }

    public function validateDocument(Document $document): void
    {
        if($this->documentSolver->isStatusDraft($document)) {
            $this->changeStatus($document, Document::STATUS_VALID);
        }
    }

    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">';
        if ($this->producerSolver->getConfig('document_image_bottom')) {
            $urlDocumentImageBottom = \Yii::$app->urlManagerProducer->getHostInfo() . '/' . \Yii::$app->urlManagerProducer->baseUrl . '/uploads/' . $producer->document_image_bottom;
            $contentFooter .= '<div class="image"><img src="'.$urlDocumentImageBottom.'" style="max-height:80px;" /></div>';
        }
        if ($this->producerSolver->getConfig('document_infos_bottom')) {
            $contentFooter .= '<div class="infos-bottom">'.nl2br($producer->document_infos_bottom).'</div>';
        }
        $contentFooter .= '</div>';

        $marginBottom = 10;
        if (strlen($this->producerSolver->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)) {
            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 sendDocument(DocumentInterface $document): bool
    {
        if (isset($document->user) && strlen($document->user->email) > 0) {
            $producer = $this->getProducerContext();

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

            $email = \Yii::$app->mailer->compose(
                [
                    'html' => '@common/mail/sendDocument-html',
                    'text' => '@common/mail/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));

            // @TODO : gérer via un événement
            $this->documentBuilder->updateDocumentIsSend($document, true);

            return $email->send();
        }

        return false;
    }
}