<?php

namespace SoftminalB2B\Services\Pdf;

if (!defined('ABSPATH')) {
    exit;
}

use SoftminalB2B\Vendor\Dompdf\Dompdf;
use SoftminalB2B\Vendor\Dompdf\Options;

/**
 * The bundled dompdf engine (FEATURES G4). Server-side, no external API.
 *
 * dompdf and its dependencies live under the scoped `SoftminalB2B\Vendor`
 * namespace ({@see lib/vendor-prefixed}) so they can never collide with a different copy of
 * the same library (e.g. Sabberworm's CSS parser) bundled by WooCommerce or
 * another plugin. Its autoloader is loaded lazily here — only when a PDF is
 * actually rendered — to keep it off every request.
 */
class DompdfEngine implements PdfEngine
{
    public function render(string $html): string
    {
        if (!class_exists(Dompdf::class, false)) {
            require_once SMB2B_DIR . 'lib/vendor-prefixed/vendor/autoload.php';
        }

        $options = new Options();

        // Remote resources are disabled on purpose: an invoice must never make
        // the server fetch an attacker-controlled URL embedded in order data.
        // The logo is inlined as a data URI by the renderer, so nothing legit
        // needs remote loading.
        $options->set('isRemoteEnabled', false);
        $options->set('isHtml5ParserEnabled', true);

        // Helvetica is one of the 14 standard PDF fonts, so it needs no bundled
        // font file — that is what lets the build drop dompdf's 7.5 MB font pack.
        // Templates render in it (Latin/European); Pro can register extra fonts
        // and non-Latin coverage by shipping font files and using @font-face.
        $options->set('defaultFont', 'Helvetica');

        // Keep dompdf's font cache inside the uploads dir, which is writable,
        // rather than letting it try to write under the plugin folder.
        $upload = wp_upload_dir();
        if (empty($upload['error'])) {
            $cache = trailingslashit($upload['basedir']) . 'smb2b-fontcache';
            wp_mkdir_p($cache);
            $options->set('fontCache', $cache);
        }

        $dompdf = new Dompdf($options);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->loadHtml($html);
        $dompdf->render();

        return (string) $dompdf->output();
    }
}
