<?php
/**
 * Dompdf wrapper for PDF generation.
 *
 * @package Kramar
 * @since   1.0.0
 */

declare( strict_types=1 );

namespace Kramar\Modules\Invoices;

defined( 'ABSPATH' ) || exit;

/**
 * Renders HTML to PDF via the vendor-prefixed Dompdf library.
 *
 * @since 1.0.0
 */
final class Pdf_Renderer {

	/**
	 * Render an HTML string to a PDF binary string.
	 *
	 * @since 1.0.0
	 *
	 * @param string $html       Full HTML document.
	 * @param string $paper_size 'a4' or 'letter'.
	 * @return string Raw PDF content.
	 */
	public static function render( string $html, string $paper_size = 'a4' ): string {
		self::load_autoloader();

		$options = new \Kramar\Vendor\Dompdf\Options();
		// Remote fetching stays OFF (SSRF safety). Local images (the logo) are
		// embedded as base64 data URIs by the block renderer, so they still render.
		$options->set( 'isRemoteEnabled', false );
		$options->set( 'isHtml5ParserEnabled', true );
		$options->set( 'defaultFont', 'sans-serif' );
		$options->set( 'isFontSubsettingEnabled', true );

		$upload_dir = wp_get_upload_dir();
		$font_dir   = trailingslashit( $upload_dir['basedir'] ) . 'kramar-invoices/fonts/';

		if ( ! is_dir( $font_dir ) ) {
			wp_mkdir_p( $font_dir );
		}

		$options->set( 'fontDir', $font_dir );
		$options->set( 'fontCache', $font_dir );

		$dompdf = new \Kramar\Vendor\Dompdf\Dompdf( $options );
		$dompdf->setPaper( $paper_size, 'portrait' );
		$dompdf->loadHtml( $html );
		$dompdf->render();

		return $dompdf->output();
	}

	/**
	 * Load the Strauss-prefixed autoloader once.
	 *
	 * @since 1.0.0
	 */
	private static function load_autoloader(): void {
		static $loaded = false;

		if ( $loaded ) {
			return;
		}

		$autoloader = KRAMAR_DIR . 'vendor-prefixed/autoload.php';
		if ( file_exists( $autoloader ) ) {
			require_once $autoloader;
		}

		$loaded = true;
	}
}
