<?php
namespace App\Core;

use Dompdf\Dompdf;
use Dompdf\Options;

class PDF
{
    public static function available(): bool
    {
        return class_exists(Dompdf::class);
    }

    /**
     * Télécharge un PDF généré à partir du HTML fourni.
     * Sécurise l’output (buffers, headers) pour éviter les PDF corrompus.
     */
    public static function download(string $html, string $filename = 'document.pdf', array $opts = []): void
    {
        if (!self::available()) {
            // Fallback: renvoyer la page d'impression HTML
            if (ob_get_length()) { @ob_end_clean(); }
            header('Content-Type: text/html; charset=utf-8');
            echo $html;
            exit;
        }
        try {
            $options = new Options();
            $options->set('isRemoteEnabled', true);
            $options->set('isHtml5ParserEnabled', true);
            $options->set('defaultFont', 'DejaVu Sans');
            // Permettre aux assets locaux (images) via chroot vers public/
            $public = realpath(__DIR__ . '/../../public');
            if ($public && is_dir($public)) { $options->setChroot($public); }
            // Overrides utilisateurs
            foreach ($opts as $k=>$v) { try { $options->set($k, $v); } catch (\Throwable $e) { /* ignore */ } }

            $dompdf = new Dompdf($options);
            $dompdf->loadHtml($html, 'UTF-8');
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();

            $output = $dompdf->output();
            // Nettoyer tout ce qui a pu être envoyé avant (warnings, espaces)
            while (ob_get_level() > 0) { @ob_end_clean(); }
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Length: ' . strlen($output));
            echo $output;
            exit;
        } catch (\Throwable $e) {
            // Fallback: renvoyer HTML pour éviter un fichier PDF corrompu
            if (ob_get_length()) { @ob_end_clean(); }
            header('Content-Type: text/html; charset=utf-8');
            echo $html;
            exit;
        }
    }

    /**
     * Stream inline dans le navigateur (au lieu de téléchargement direct)
     */
    public static function streamInline(string $html, string $filename = 'document.pdf', array $opts = []): void
    {
        if (!self::available()) {
            if (ob_get_length()) { @ob_end_clean(); }
            header('Content-Type: text/html; charset=utf-8');
            echo $html;
            exit;
        }
        try {
            $options = new Options();
            $options->set('isRemoteEnabled', true);
            $options->set('isHtml5ParserEnabled', true);
            $options->set('defaultFont', 'DejaVu Sans');
            $public = realpath(__DIR__ . '/../../public');
            if ($public && is_dir($public)) { $options->setChroot($public); }
            foreach ($opts as $k=>$v) { try { $options->set($k, $v); } catch (\Throwable $e) { /* ignore */ } }

            $dompdf = new Dompdf($options);
            $dompdf->loadHtml($html, 'UTF-8');
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $output = $dompdf->output();
            while (ob_get_level() > 0) { @ob_end_clean(); }
            header('Content-Type: application/pdf');
            header('Content-Disposition: inline; filename="' . $filename . '"');
            header('Content-Length: ' . strlen($output));
            echo $output;
            exit;
        } catch (\Throwable $e) {
            if (ob_get_length()) { @ob_end_clean(); }
            header('Content-Type: text/html; charset=utf-8');
            echo $html;
            exit;
        }
    }
}

