<?php
declare(strict_types=1);

function mpdf_make(string $html, string $filename = 'report.pdf'): void
{
    // Ensure composer autoload
    $autoload = __DIR__ . '/../vendor/autoload.php';
    if (file_exists($autoload)) {
        require_once $autoload;
    }

    // Support both mPDF v7+ (namespaced) and v6 (legacy class name)
    if (class_exists('\Mpdf\Mpdf')) {
        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4',
            'default_font' => 'dejavusans',
            'margin_left' => 10,
            'margin_right' => 10,
            'margin_top' => 12,
            'margin_bottom' => 12,
        ]);
        $mpdf->SetDirectionality('rtl');
        $mpdf->WriteHTML($html);
        $mpdf->Output($filename, \Mpdf\Output\Destination::DOWNLOAD);
        exit;
    }

    if (class_exists('\mPDF') || class_exists('mPDF')) {
        // mPDF v6
        $mpdf = new \mPDF('utf-8', 'A4');
        $mpdf->SetDirectionality('rtl');
        $mpdf->SetFont('dejavusans', '', 12);
        $mpdf->WriteHTML($html);
        $mpdf->Output($filename, 'D'); // Download
        exit;
    }

    http_response_code(500);
    die('mPDF غير متاح. تأكد من وجود vendor/autoload.php');
}
