<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: WYSIWYGPDFView.php,v 1.4.8.2 2026/03/31 14:34:05 jparis Exp $

namespace Pmb\DSI\Models\View\WYSIWYGPDFView;

use Pmb\DSI\Models\Diffusion;
use Pmb\DSI\Models\Item\Item;
use Pmb\Common\Library\HTML2PDF\HTML_2_PDF;
use Pmb\DSI\Models\View\WYSIWYGView\WYSIWYGView;
use Pmb\DSI\Models\View\WYSIWYGPDFView\Render\PDFRenderer;
use Pmb\Common\Library\MPDF\PMB_MPDF;
use Mpdf\Output\Destination;

class WYSIWYGPDFView extends WYSIWYGView
{
    public function render(Item $item, int $entityId, int $limit, string $context)
    {
        $this->entityId = $entityId;
        $this->limit = $limit;
        $this->context = $context;

        $rootElement = $this->settings->layer->blocks[0];
        if (empty($rootElement)) {
            return "";
        }

        $diffusion = new Diffusion($entityId);
        $name = "attachment" . $this->id;

        foreach ($diffusion->settings->attachments as $attachment) {
            if ($attachment->view == $this->id) {
                $name = $attachment->name;
            }
        }

        $renderer = new PDFRenderer($this, $item);

        $mpdf = new PMB_MPDF();
        $html = $renderer->render($rootElement, true);
        $mpdf->WriteHTML($html);
        $mpdf->SetTitle($name);
        $content = $mpdf->Output($name, Destination::STRING_RETURN);

        return [
            "nomfichier" => $name . ".pdf",
            "contenu" => $content,
        ];
    }

    public function preview(Item $item, int $entityId, int $limit, string $context)
    {
        return $this->render($item, $entityId, $limit, $context);
    }

    protected function formatHTML(string $body, bool $html5 = true)
    {
        global $opac_default_style;

        $html = \HtmlHelper::getInstance()->getStyleOpac($opac_default_style);
        $html .= $body;
        return $html;
    }
}
