<?php
declare(strict_types=1);

namespace App\Service\Export\Encoder;

use App\Enum\Export\ExportFormatEnum;
use \Knp\Snappy\Pdf;

/**
 * Encode HTML to PDF
 */
class PdfEncoder implements EncoderInterface
{
    /**
     * Default encoding options
     * @see https://wkhtmltopdf.org/libwkhtmltox/
     *
     * @var array<mixed>
     */
    private array $defaultOptions = [
        'margin-top'    => 35,
        'margin-right'  => 10,
        'margin-bottom' => 15,
        'margin-left'   => 15,
        'header-spacing'   => 5,
        'enable-local-file-access' => true
    ];

    public function __construct(
        private Pdf $knpSnappy
    ) {}

    public function support(string $format): bool {
        return $format === ExportFormatEnum::PDF()->getValue();
    }

    /**
     * Default encoding options
     * @return array<mixed>
     */
    public function getDefaultOptions() {
        return $this->defaultOptions;
    }

    /**
     * Encode the given HTML content into PDF, and
     * return the encoded content
     *
     * @param string $html
     * @param array<mixed> $options
     * @return string
     */
    public function encode(string $html, array $options = []): string
    {
        $options = array_merge($this->getDefaultOptions(), $options);

        return $this->knpSnappy->getOutputFromHtml($html, $options);
    }
}
