<?php

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

class AIEO_Fulfillment_PDF_Engine {

    
    public static function available_class() {
        
        
        if (class_exists('AIEO_Pro_PDF_Engine')) {
            AIEO_Pro_PDF_Engine::boot();
        }
        if (class_exists('\\Dompdf\\Dompdf')) { return '\\Dompdf\\Dompdf'; }

        
        
        
        if (class_exists('\\WPO\\IPS\\Vendor\\Dompdf\\Dompdf')) {
            if (function_exists('WPO_WCPDF')) {
                $wpo = WPO_WCPDF();
                if (is_object($wpo) && property_exists($wpo, 'main')) { $wpo->main; }
            }
            return '\\WPO\\IPS\\Vendor\\Dompdf\\Dompdf';
        }
        return '';
    }

    
    public static function render($html, array $options = array()) {
        
        
        if (class_exists('AIEO_Pro_PDF_Engine') && AIEO_Pro_PDF_Engine::available()) {
            return AIEO_Pro_PDF_Engine::render($html, $options);
        }

        
        
        $cls = self::available_class();
        if ($cls === '') {
            return new WP_Error('no_pdf_engine', __('No DOMPDF library available. Activate ai-eshop-optimizer-pro (which bundles DOMPDF 3.1.5).', 'ai-eshop-optimizer'));
        }
        $paper       = isset($options['paper'])       ? (string) $options['paper']       : 'a4';
        $orientation = isset($options['orientation']) ? (string) $options['orientation'] : 'portrait';

        try {
            $dompdf = new $cls(array(
                'isHtml5ParserEnabled' => true,
                'isRemoteEnabled'      => true,
                'defaultFont'          => 'DejaVu Sans',
                'chroot'               => array(WP_CONTENT_DIR, ABSPATH),
            ));
            $dompdf->loadHtml((string) $html, 'UTF-8');
            $dompdf->setPaper($paper, $orientation);
            $dompdf->render();
            return (string) $dompdf->output();
        } catch (\Throwable $e) {
            return new WP_Error('dompdf_render_failed', $e->getMessage());
        }
    }
}
