<?php
declare(strict_types=1);

namespace App\Lib;

use Mpdf\Mpdf;

/**
 * Thin mPDF wrapper for orchview2 reports.
 * Callers pass HTML; we render + stream / return the PDF bytes.
 */
final class Pdf
{
    public static function render(string $html, string $title = 'Report'): Mpdf
    {
        $tmp = STORAGE . DS . 'mpdf-tmp';
        if (!is_dir($tmp) && !@mkdir($tmp, 0775, true) && !is_dir($tmp)) {
            throw new \RuntimeException('Cannot create mpdf-tmp: ' . $tmp);
        }
        $mpdf = new Mpdf([
            'tempDir'        => $tmp,
            'default_font'   => 'sans-serif',
            'default_font_size' => 10,
            'margin_left'    => 12,
            'margin_right'   => 12,
            'margin_top'     => 12,
            'margin_bottom'  => 12,
        ]);
        $mpdf->SetTitle($title);
        $mpdf->SetAuthor(APP_NAME);
        $mpdf->WriteHTML($html);
        return $mpdf;
    }

    public static function stream(string $html, string $filename): void
    {
        self::render($html, $filename)->Output($filename . '.pdf', 'I');
    }

    public static function download(string $html, string $filename): void
    {
        self::render($html, $filename)->Output($filename . '.pdf', 'D');
    }
}
