<?php

namespace App\Domain\Pdf;

use App\Models\TreatmentPlan;

/**
 * Renders the treatment plan PDF with mPDF (chosen for proper Arabic
 * shaping + RTL — composer require mpdf/mpdf).
 * Reused in v2.1-C to attach plan PDFs to WhatsApp messages (M5).
 */
class TreatmentPlanPdf
{
    public function render(TreatmentPlan $plan): string
    {
        if (! class_exists(\Mpdf\Mpdf::class)) {
            abort(500, 'mPDF is not installed. Run: composer require mpdf/mpdf');
        }

        $plan->load(['patient', 'dentist', 'items.procedure', 'tenant']);

        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4',
            'directionality' => app()->getLocale() === 'ar' ? 'rtl' : 'ltr',
            'autoScriptToLang' => true,
            'autoLangToFont' => true,
            'margin_top' => 14,
            'margin_bottom' => 14,
        ]);

        $mpdf->SetTitle(__('Treatment plan').' — '.$plan->patient->full_name);
        $mpdf->WriteHTML(view('pdf.treatment-plan', ['plan' => $plan])->render());

        return $mpdf->Output('', \Mpdf\Output\Destination::STRING_RETURN);
    }

    public function filename(TreatmentPlan $plan): string
    {
        return 'treatment-plan-'.$plan->uuid.'.pdf';
    }
}
